blue-sky blue-sky - 13 days ago 10
Java Question

Getting class name for logging

To log errors for a given class, I'm accessing the class name like so:
Is this a 'good' way to return the class name as a String, so it can be used for logging?

private static final String CLASS_NAME = MyClass.class.getName();
logger.error("Error occurred in "+CLASS_NAME);

Answer

You can set up your logging parameters in log4j.xml itself.

For exp -

<appender name="swcd-web" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="Threshold" value="DEBUG"/>
    <param name="Append" value="true"/>
    <param name="File" value="${catalina.home}/logs/swcd-web.log"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
    </layout>
</appender>

It would log exceptions like this in swcd-web.log file -

2012-05-23 16:34:51,632 [main] ERROR com.idc.sage.sso.dynamo.SsoDbStorage - cannot get configuration for max SSO age