Logging Packages with Log4J

1 min read
[@021]

The Pulse

Erik's Pulse has been published.

[@570]

Logging Packages with Log4J

I was looking for a way to log a specific package to its own file using Log4J. Took me a while to figure it out, but here's what I came up with in my log4j.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- Main Rolling Log (by Size) --> <appender name="R" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="main.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="10MB"/> <param name="maxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n"/> </layout> </appender>
<!-- MyPackage Rolling Log --> <appender name="P" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="mypackage.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="10MB"/> <param name="maxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n"/> </layout> </appender>
<!-- MyPackage Logger --> <logger name="net.thauvin.erik.mypackage" additivity="false"> <appender-ref ref="P"/> </logger>
<!-- Print only messages of priority INFO or above in the com.example package --> <category name="com.example"> <priority value="info"/> </category>
<!-- Root (Default) Logging --> <root> <priority value="fatal"/> <appender-ref ref="R"/> </root>
</log4j:configuration>

Incidentally, Log4j 1.2.13 was just released.