Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - how to log only one level with log4j2?

I'm using log4j2 in my application.

What I want is everything up to 'debug' to go to console, everything up to 'info' to go to myapp.log, and ONLY 'info' to go to 'myapp-audit.log'.

The reason is, INFO mostly consists of successful modifications to data (ex. 'user created', 'user updated', 'user deleted', and so on). If is effectively an audit log of data modifications.

But I can't get figure out how to do it.

How do I get ONLY 'info' to get logged to 'myapp-audit.log'? Here's my current configuration ...

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>

        <File name="LogFile" fileName="myapp.log">
            <PatternLayout
                pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>

        <File name="AuditFile" fileName="myapp-audit.log">
            <PatternLayout
                pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </appenders>

    <loggers>
        <root level="debug">
            <appender-ref ref="Console" level="debug" />
            <appender-ref ref="LogFile" level="info" />
            <appender-ref ref="AuditFile" level="info" /> <!-- I want ONLY 'info' here -->
        </root>
    </loggers>
</configuration>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you specify INFO in the appender-ref, the appender will receive INFO, WARN, ERROR and FATAL events. You can further restrict to only INFO by filtering out WARN, ERROR and FATAL level events:

<File name="AuditFile" fileName="myapp-audit.log">
    <PatternLayout 
       pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%nZ" />
    <Filters>

        <!-- First deny warn, error and fatal messages -->
        <ThresholdFilter level="warn"  onMatch="DENY" onMismatch="NEUTRAL"/>
        <ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
        <ThresholdFilter level="fatal" onMatch="DENY" onMismatch="NEUTRAL"/>

        <!-- Then accept info, warn, error, fatal and deny debug/trace -->
        <ThresholdFilter level="info"  onMatch="ACCEPT" onMismatch="DENY"/>
    </Filters>
</File>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...