1

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  
APC
  • 144,005
  • 19
  • 170
  • 281
user960740
  • 79
  • 1
  • 2
  • 7

3 Answers3

2

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);
Robert
  • 39,162
  • 17
  • 99
  • 152
0

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

Community
  • 1
  • 1
AlexR
  • 114,158
  • 16
  • 130
  • 208
0

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
MaDa
  • 10,511
  • 9
  • 46
  • 84
  • @user960740 Log4j has a built-in default initialization within a static code block that's likely executed before you have a chance to do something about it. This environment variable prevents this execution. You may want to do this to make sure you're starting with exactly the configuration you want. – MaDa Sep 27 '11 at 08:50