简体   繁体   中英

Log4J dynamically create log file

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);

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.

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