Log the user sessionID or username or user id with every log message
Posted By : Ankush Kocher | 18-Nov-2014
In this blog Logging additional information like SessionID in every Log4j message and explained the concept of the Mapped Diagnostic Context (MDC) – a thread -local key-value store that can be accessed from the Log4j conversion pattern. We will use the MDC to log the user’s SessionID or any user or session related information.
Modify your Log4j config in Config.groovy and put a placeholder for the sessionId into your conversion pattern:
log4j = { appenders { console name: 'stdout', layout: pattern(conversionPattern: '[%d{HH:mm:ss}] %X{sessionId} %p %c{1} - %m%n')
Now we have to fill the sessionId variable for each request. Create a new filter class named LoggingFilters in grails-app/conf:
import org.springframework.web.context.request.RequestContextHolder import org.slf4j.MDC class LoggingFilters { def filters = { all(controller:'*', action:'*') { before = { String sessionId = RequestContextHolder.getRequestAttributes()?.getSessionId() if(sessionId){ MDC.put('sessionId', sessionId) } } after = { } afterView = { MDC.remove('sessionId') } } } }
This filter will get invoked before every controller action, extract the session id from the request and put it into the MDC. After every view rendering, the sessionId will be removed from the MDC (clean it up).
appenders { appender new DailyRollingFileAppender( name: 'myFileAppender', datePattern: "'.'yyyy-MM-dd", layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss} %X{sessionId} %m%n'), file: "search.log" ) }
%X{sessionId} is set in Filter code. %m is the string pass in log.debug function and %n foe new line %d{dd-MM-yyyy HH:mm:ss} id for date
We can add more variable in conversionPattern and set there value using org.slf4j.MDC
debug myFileAppender 'grails.app.controllers.com.test.UserController'
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankush Kocher
Ankush is a bright web app developer with expertise in Groovy and Grails development. Ankush is also an expert AngularJS developer.