运行AsyncAppender示例时出错

时间:2014-01-05 07:06:00

标签: java logging log4j

以下是log4j xml配置文件:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">    
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
             <param name="ConversionPattern" 
                            value="%d %-5p [%t]  - %m%n"/>
        </layout>
    </appender>
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
                <appender-ref ref="CONSOLE"/>
    </appender>
    <logger name="com.apress.logging.log4j" additivity="false">
             <level value="debug"/>
             <appender-ref ref="ASYNC"/>
             <appender-ref ref="CONSOLE"/>
    </logger>
    <root>
        <priority value="debug"/>
        <appender-ref ref="ASYNC"/>
        <appender-ref ref="CONSOLE"/>       
    </root>
</log4j:configuration>

以下是源代码:

/*
 * AsyncLogging.java
 */

package com.apress.logging.log4j;

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;
/** This class demonstrates the asynchronous logging
 */
public class AsyncLogging 
{

    private static Logger logger = Logger.getLogger(AsyncLogging.class.getPackage().getName());
    private AsyncAppender asyncAppender = null;
    private ConsoleAppender consoleAppender = null;

    /** Creates a new instance of AsyncLogging */
    public AsyncLogging() 
    {

        try {
            logger.setAdditivity(false);
            consoleAppender = (ConsoleAppender)logger.getRootLogger().getAppender("CONSOLE");
            asyncAppender = (AsyncAppender)logger.getRootLogger().getAppender("CONSOLE");
            asyncAppender.setBufferSize(4);
        }catch(Exception e) {
            System.out.println("error: "+e.toString());
        }

    }

    /** This method simply logs the messages
     */    
    public void doLogging() 
    {
        logger.debug("Hello 1");
        logger.debug("Hello 2");
        logger.debug("Hello 3");
        logger.debug("Hello 4");
        logger.debug("Hello 5");
        //LogManager.shutdown();
    }

    /** the main method
     */    
    public static void main(String args[]) 
    {
        AsyncLogging demo = new AsyncLogging();
        demo.doLogging();
    }

}

我无法得到正确的结果。输出有问题:

*log4j:WARN No appenders could be found for logger (com.apress.logging.log4j).
log4j:WARN Please initialize the log4j system properly.*

请帮我找出错误的地方,非常感谢。

0 个答案:

没有答案