Log4J dynamically create log file

£可爱£侵袭症+ 提交于 2019-12-07 12:18:44

问题


I have successfully created a log at each process run time. The issue I am having now is any packages that are called that are not children of the current running process does not write its log to my file. For example I create a new log file called running-.log. The process that is running is com.me.foo inside of this class there is a call to a method in com.you and another one in com.zee . I would like to have com.you and com.zee logs write to the running-.log and not to the console log. It isn't as simple as just changing the getLogger() method to be a child of com.me.foo. Some of the logs are written out from third party jars. I am at a loss. If you need to see more code or some additional info, please let me know. There has to be another way to handle this.

Thanks

Code to create the log file dynamically

public void createLogInstance(String packaging,String appenderName, String logFileName){
  Logger logger = Logger.getLogger(packaging);

  Appender fileAppender = logger.getAppender(appenderName);

  if(fileAppender != null){
     logger.removeAppender(fileAppender);
  }

  //Create the root appender
  ConsoleAppender console = new ConsoleAppender();

  String pattern = ....;
  console.setLayout(new PatternLayout(pattern));
  console.setThreshold(Level.FATAL);
  console.activateOptions();

  logger.addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName(appenderName);
  fa.setFile(logFileName);
  fa.setLayout(new PatternLayout(..));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();
  logger.setAdditivity(false);

  logger.addAppender(fa);


}

com.zee log

private static Logger logger = LoggerFactory.getLogger(Zee.class);

com.you log

private static Logger logger = LoggerFactory.getLogger(You.class);

回答1:


I was missing the rootLogger. Changed this line

Logger logger = Logger.getLogger(packaging);

to

Logger logger = Logger.getRootLogger();

If someone has a better way please let me know.



来源:https://stackoverflow.com/questions/20645052/log4j-dynamically-create-log-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!