tarunkumar tarunkumar - 4 months ago 42
Java Question

Approach to write log to different log files based upon tenant in muti-tenant application using log4j

In a multi tenant application I want that separate files should get created for different tenants using log4j. What could be the best possible pattern to do it without cluttering the code.

Answer

If you have one application for all of yours "tenants", you can use MDC and a MDCSiftingAppender :

log4j.appender.sift=org.apache.log4j.sift.MDCSiftingAppender
log4j.appender.sift.key=tenant
log4j.appender.sift.default=default
log4j.appender.sift.appender=org.apache.log4j.FileAppender
log4j.appender.sift.appender.layout=org.apache.log4j.PatternLayout
log4j.appender.sift.appender.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %m%n
log4j.appender.sift.appender.file=log/$\\{tenant\\}.log
log4j.appender.sift.appender.append=true

and in your code, around a code for a 'tenant' (ideally, a web request filter, or something like that) :

MDC.put("tenant", xxx)
...
MDC.remove("tenant")