Showing posts with label log4j. Show all posts
Showing posts with label log4j. Show all posts

Tuesday, March 9, 2010

log4j: How to compress log files and save instead of log rotation

You can use this method if you want to save all the log files in your production server and keep it there for ever.

Steps:


2. Use a similar configuration. Key is to use TimeBasedRollingPolicy

<appender name="RFA" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Threshold" value="DEBUG"/>
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="ActiveFileName" value="app.log"/>
<param name="FileNamePattern" value="app_%d{yyyyMMdd-HH}.log.gz"/>
</rollingPolicy>
<!-- param name="Append" value="true"/ -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n"/>
</layout>
</appender>

Configuration explained in detail
Appender name - just a string to name the appender I used "RFA"

Threshold - Default threshold value for the appender. I used DEBUG to log everything

Rolling policy class - TimeBasedRollingPolicy this triggers a time based rolling policy. see the conversion pattern for more details

Active file name - Self explanatory I used app.log

File Name Pattern -
  • "app_" is the prefix for the compressed file
  • %d{yyyyMMdd-HH} triggers two things. one compressed log file name in specified date format. Also triggers hourly rotation since HH is specified. For daily rotation you can remove -HH
  • .log.gz triggers the compression. the compressed file will be in .gz format

Pattern layout - pattern layout for each log line


Use this feature only if it is really neccessary for your project. log4j 1.3 alpha is an abandoned release and no idea why is that abandoned. But unfortunately TimeBasedRollingPolicy is not available in any of the other log4j versions. But if you are looking for this feature, go ahead and use it. I can give you guarantee, it is working in my project in production for last 3 years.

Cheers!

Tuesday, April 21, 2009

When to use log.isDebugEnabled()

Logging statements are essential for any standard application. Usually log levels are configured at system level. That is developers just need to write log.debug() statements and forget about while they run or not in various enviornments.

But as a developer, make sure you use log.isDebugEnabled in places where it is appropriate. You don't want to wrap all the log.debug statements. That wont gain you much performance, instead increase code cluttering.

One best place I would suggest is when you try to print a object which has a large toString method with a reflection to string implementation or so.

So,

I use log.debug("Start")

and

if (log.isDebugEnabled()) {
log.debug(complexObject.toString());
}