Reputation: 1314
In linux the user name is given by $USER environment variable.
Say I have following log4j config
log4j.rootLogger=info, infoApp
# this should contain only INFO messages
log4j.appender.infoApp=org.apache.log4j.RollingFileAppender
log4j.appender.infoApp.File=/mylogs/logs/app/app.info.log
log4j.appender.infoApp.layout=org.apache.log4j.PatternLayout
log4j.appender.infoApp.layout.ConversionPattern=%d [%-5p] %t -- %m%n
log4j.appender.infoApp.MaxFileSize=10MB
log4j.appender.infoApp.MaxBackupIndex=6
How can I dynamically add user name for the app which uses this file in the file name so that the user1 logs go into /mylogs/logs/app/app.user1.info.log and user2 logs go into /mylogs/logs/app/app.user2.info.log?
I am using log4j 1.2.14 but can upgrade if needed. Log4j is also being used by other libraries whose source code I do not want to touch. My application is a standalone Java app.
If I change the file name in config to /mylogs/logs/app/app.${env.USER}.info.log (assuming I upgrade to log4j 2.3), it does the substitution at deployment time to change the log4j.properties file itself. I want the user substitution to happen at run time so same installation can be used by multiple users.
Thanks!
Upvotes: 0
Views: 1494
Reputation: 2534
At runtime, you could create a new FileAppender and add it to the root logger, i.e.
FileAppender fileAppender = new FileAppender();
fileAppender.setFile("userxylog.log");
....
Logger.getRootLogger().addAppender(fileAppender)
....
this is documented here https://logging.apache.org/log4j/1.2/apidocs/
Upvotes: 1