Java – log4j Add logs to different files depending on who is logged in to the application

log4j Add logs to different files depending on who is logged in to the application… here is a solution to the problem.

log4j Add logs to different files depending on who is logged in to the application

I’m using log4j.1.2.16 to log in to 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 (same application). For example, if user1 logs in to my application, I want the logs to go into the user1.log file. I’ll include the logged-in user information in the session object and static thread-local variables.
How can I do this?

Solution

Here are a few ways to achieve this.

  1. You can achieve this using RoutingAppender.
  2. Configure logging programmatically as mentioned here
  3. If you can switch to Logback, think of MDC with SiftingAppender

Note: Many of these solutions require you to set the UserId in a shared context such as MDC or ThreadContext, so be sure to clear the request after it is processed.

Related Problems and Solutions