other register

Wednesday, May 14, 2008

Write Logs to Different Files Using Log4J

If you have one generic java program to transform xml files from different directory.

java -Dfile_properties=/path/to/ -jar YourProgramm.jar

You can specify different input directory using the "-D" parameter in the command line.

In each file, you specify:


Because you might want different logs for different transformations from different source, thus you can spot on which source file cause the problem.

By default, if you don't specify where to load the log4j configurations, it will load the, and then log4j.xml from the class folder, which would be uneditable when put in a jar. This might not what you want. You want to specify an external log4j configuration which you can edit outside of the program.

Here is what you can do:

Put the xml log4j file (e.g. xmllog4jconfig.xml) in the project directory.

In your java program

Public class Transformer {

private static Logger logger = Logger.getLogger(SaxonTransform.class);

public static void main(String[] args) {

logger.debug("Here is some DEBUG");"Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");

In the log4j xml configuration file, you can use LevelRange filter to log different levels of information into different log files like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >

<!-- log without a filter -->
<appender name="file"
<param name="File" value="logs/test.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

<!-- log with a filter -->
<appender name="debugfile"
<param name="File" value="logs/debug.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

<!-- set the filter -->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="debug" />
<param name="LevelMax" value="debug" />

<priority value="debug"></priority>
<appender-ref ref="debugfile" />
<appender-ref ref="file" />

For more tutorials on Log4J, please have a look at:

Log4J Tutorial from The University Of Birmingham
Log4J Tutorial from Laliluna

No comments: