Log4j logging to separate files

别来无恙 提交于 2019-12-11 05:55:16

问题


I have an application that listens on a specific port to do its task. This application can run on multiple instances by specifying different ports in the argument.

MyApp-1211.bat contains

java MyApp 1211

MyApp-1311.bat contains

java MyApp 1311

MyApp-1411.bat contains

java MyApp 1411

This application logs to a file. The problem is all three instances log into a single file, myApp.log. Is there a way to tell log4j to use different log files? like:

myApp-port1211.log  
myApp-port1311.log  
myApp-port1411.log  

回答1:


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

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

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



回答2:


You can refer to system properties in log4j.xml as following:

<appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">
                <!-- The active file to log to -->
                <param name="file" value="mylog${MY_PARAM}.log" />
</appender>

Now you just have to insert your parameter into system properties either programmatically System.setProperty("MY_PARAM", args[0]) into your main() method or when you are running java:

java -DMY_PARAM=1234 MyApp 1234

Obiously you can avoid dupplication if you are running you application from bat or shell script like:

java -DMY_PARAM=%1 MyApp %1

Please see the following references for details:

http://wiki.apache.org/logging-log4j/Log4jXmlFormat

Using system environment variables in log4j xml configuration




回答3:


If you go for loading the property configuration file yourself, as suggested by other answers, don't forget to disable the log4j default initialization by adding the env. variable definition to your program's command line:

-Dlog4j.defaultInitOverride=true


来源:https://stackoverflow.com/questions/7565756/log4j-logging-to-separate-files

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