log4j add logs in different files based on logged in user of the application

Viewed 1067

I am using log4j.1.2.16 for logging in my Java application hosted in tomcat. Given below is my log4j.properties

##DEBUG < INFO < WARN < ERROR < FATAL
#### Use two appenders, one to log to console, another to log to a file
log4j.rootCategory=DEBUG, R

#### Appender writes to a file
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${APP_HOME}/runtime/log/em.log

# Control the maximum log file size
log4j.appender.R.MaxFileSize=100MB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=20

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %c{1} %m%n

log4j.logger.com.mchange=WARN
log4j.logger.com.amazonaws=WARN
log4j.logger.org.hibernate=ERROR
log4j.logger.org.apache.commons.beanutils=WARN
log4j.logger.org.apache.commons.httpclient=WARN
log4j.logger.org.elasticsearch=WARN
log4j.category.velocity=WARN
log4j.com.amazonaws.services.s3=WARN
log4j.org.apache.http.impl.conn.Wire=WARN
log4j.logger.httpclient.wire.header=WARN
log4j.logger.httpclient.wire.content=WARN

I want to maintain different log files for different users(of the same application). For example if user1 logs in to my application I want the logs to go into user1.log file . I will be having loggedin user information in the session object and a static thread local variable. How can I achieve this ?

1 Answers

Here are few ways to achieve this.

  1. You can make use of RoutingAppender to achieve this.
  2. Configure the Logging Programmatically like mentioned here.
  3. If you can change to Logback, You can think of MDC with SiftingAppender.

Note : Many of these solutions require you to set the UserId in a shared context like MDC or ThreadContext, so make sure you clear it out after the request processing.

Related