Monday, May 16, 2011

User tracking logging in Grails

Hi peeps

Thought i would just do a quick post about how to create a custom logging filter for logging which pages a user went to.

First setup log4j config to add a new apppender nd logger called utlog (usage tracking)

 def utLog = "${System.properties.getProperty('catalina.base')}${File.separator}logs${File.separator}utlog.log"  
println utLog
log4j = {
appenders {
rollingFile name: 'utlog', file: utLog, layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS}|%p|%c{1}|%X{userId}|%X{sessionId}|%m%n'), maxFileSize: '10MB', threshold: org.apache.log4j.Level.DEBUG
console name: 'stdout', layout:pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS}|%p|%c{1}|%X{userId}|%X{sessionId}|%m%n'), threshold: org.apache.log4j.Level.DEBUG
}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
warn 'org.mortbay.log'
info utlog: ['ut'],additivity:true
}



Next create a filter that uses Spring security plugin to fetch the current logged in user:

 class UsageTrackingFilters {  
def springSecurityService
private static final Log usagetrackingLog = LogFactory.getLog('ut')
def filters = {
all(controller: '*', action: '*') {
before = {
String sessionId = RequestContextHolder.getRequestAttributes()?.getSessionId()
if (sessionId) {
MDC.put('sessionId', sessionId)
}
if (springSecurityService.isLoggedIn()) {
def userId = springSecurityService.getPrincipal().id
MDC.put('userId', userId + "")
}else{
MDC.put('userId', "0")
}
usagetrackingLog.info(request.getRequestURI())
}
after = {
}
afterView = {
MDC.remove('sessionId')
MDC.remove('userId')
}
}
}
}


That is it

2 comments:

Burt said...

userId + "" should be userId.toString() in Groovy and String.valueOf(userId) in Java (or Groovy) - concatenating an empty string wastefully creates a new StringBuffer

Anonymous said...

Can I ask what 'MDC' is ?