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 c开发者_如何学运维ontains
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
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);
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
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
精彩评论