1

I want to log all server related logs (like startup and shutdown) to one file and all Hibernate SQL related logs to a different file using Log4J. I am trying to filter all irrelevant logs to see just the SQL queries. Any idea or suggestions if there is a way we can achieve it?

Thanks.

Guest
  • 17
  • 6

1 Answers1

0

You can do that if you use two different appenders, as is shown in the following configuration file (XML): 1

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- DEFAULT appender -->
    <appender name="DEFAULT" class="org.apache.log4j.FileAppender">
        <param name="file" value="default.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="conversionPattern"
                   value="%d{yyyyMMdd-HHmmss.SSS} %-5p (%c.java:%L).%M - %m%n" />
        </layout>
    </appender>

    <!-- HIBERNATE appender -->
    <appender name="HIBERNATE" class="org.apache.log4j.FileAppender">
        <param name="file" value="hibernate.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="conversionPattern" 
                   value="%d{yyyyMMdd-HHmmss.SSS} %m%n" />
        </layout>
    </appender>

    <!-- categories -->
    <category name="org.hibernate.SQL" additivity="false">
        <priority value="DEBUG" />
        <appender-ref ref="HIBERNATE" />
    </category>

    <!-- root -->
    <root>
        <priority value="INFO" />
        <appender-ref ref="DEFAULT" />
    </root>

</log4j:configuration>

Using categories (category), you can easily configure the appender destination (appender-ref) and if you want to log in the default appenders (additivity="false").


Notes

  1. log4j look for the log4j.xml file automatically in the classpath of the application (the default package or resources directory)
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • Sweet!!! Thank you, Paul. I just tried that and its working the way I wanted it to. This is very helpful since I was having difficulties in reading SQL Quries from the huge pile of server logs. Thanks again! – Guest Aug 21 '14 at 19:03
  • @user3882649 You're welcome. Don't forget that if an answer was helpful, you can [accept it](http://meta.stackoverflow.com/a/5235/227183). ;) – Paul Vargas Aug 21 '14 at 19:39
  • Great!! I didn't know that. Just did it :). Thanks for letting me know. – Guest Aug 21 '14 at 19:49