且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Log4j 日志记录到单独的文件

更新时间:2023-01-13 12:52:56

当然可以.一种方法是创建多个配置文件(log4j.xml/log4j.properties)-每个端口分别处理一个.加载配置文件后,您可以根据当前端口号选择正确的文件:

Of course you can. One way would be to create multiple configuration files (log4j.xml / log4j.properties) - one per port respectively process. Upon loading the configuration file you could select the correct one based on the current port number:

PropertyConfigurator.configure("log4j-" + port + ".properties");

相应地创建配置文件: log4j-1211.properties log4j-1311.properties ,...

Create the config files accordingly: log4j-1211.properties, log4j-1311.properties, ...

另一种选择是在运行时通过Java代码配置文件记录:

The alternative would be to configure the file logging at runtime via Java code:

String logFilename = "./myApp-port" + port + ".log";
Layout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c{1}: %m%n");
FileAppender fileAppender = new FileAppender(layout, logFilename, false);
fileAppender.setThreshold(Level.DEBUG);
Logger.getRootLogger().addAppender(fileAppender);