Logging server logs to one file and SQL logs to an

2019-02-28 07:36发布

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.

1条回答
叼着烟拽天下
2楼-- · 2019-02-28 08:20

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)
查看更多
登录 后发表回答