简体   繁体   中英

log4j creating dynamic file name based on who is logged into linux

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!

At runtime, you could create a new FileAppender and add it to the root logger, ie

  FileAppender fileAppender = new FileAppender();
  fileAppender.setFile("userxylog.log");
  ....
  Logger.getRootLogger().addAppender(fileAppender)
  ....  

this is documented here https://logging.apache.org/log4j/1.2/apidocs/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM