Logback:如何将日志写入文件

时间:2016-05-30 21:52:41

标签: java gradle logback

我需要将logback添加到我的项目中。 这是我的测试类:

public class Head implements Runnable {
    Thread trd;

    Head() {
        trd = new Thread(this);
        trd.start();
    }
    static Logger logger = LoggerFactory.getLogger(Head.class);

    @Override
    public void run() {
        MDC.put("logName", "LOG_NAME");
        logger.warn("test1");
        logger.info("test2");
        logger.error("test");
        MDC.remove("logName");
    }

    public static void main(String[] args) {
        String URL = "logback-test.xml";
        System.out.println(ClassLoader.getSystemResource(URL));
        int count = 1;
        while(count<=3){
            Head head = new Head();
            count++;
        }
    }
}

以下是我的logback-test.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">

        <discriminator>
            <key>logName</key>
            <defaultValue>test</defaultValue>
        </discriminator>
        <sift>
            <appender name="FILE-${logName}" class="ch.qos.logback.core.FileAppender">
                <file>D:/tmp/${logName}.log</file>
                <append>false</append>
                <layout class="ch.qos.logback.classic.PatternLayout">
                    <pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern>
                </layout>
            </appender>
        </sift>
    </appender>

    <root level="ALL">
        <appender-ref ref="FILE" />
    </root>
</configuration>

我添加了以下groovy依赖项:

compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'
compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.21'
compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.7'
compile group: 'ch.qos.logback', name: 'logback-core', version: '1.1.7'
compile group: 'ch.qos.logback', name: 'logback-access', version: '1.1.7'

结果我希望日志会保存到文件D:/tmp/LOG_NAME.log中,但是日志只写入控制台。你能帮忙解决这个问题吗?

添加调试选项后,我收到错误:

Failed to instantiate [ch.qos.logback.classic.LoggerContext]
         Reported exception:
              file:/D:/my_tests/build/resources/main/logback-test.xml
              groovy.lang.MissingMethodException: No signature of method: static ch.qos.logback.core.status.OnConsoleStatusListener.addNewInstanceToContext() is applicable for argument types: (ch.qos.logback.classic.LoggerContext) values: [ch.qos.logback.classic.LoggerContext[default]]
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1500)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1486)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at ch.qos.logback.classic.gaffer.GafferConfigurator.run(GafferConfigurator.groovy:65)
at ch.qos.logback.classic.gaffer.GafferConfigurator$run.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at ch.qos.logback.classic.gaffer.GafferConfigurator.run(GafferConfigurator.groovy:44)
at ch.qos.logback.classic.gaffer.GafferUtil.runGafferConfiguratorOn(GafferUtil.java:43)
at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:67)
at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
at com.aerlingus.uita.utils.Head.<clinit>(Head.java:20)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:122)

3 个答案:

答案 0 :(得分:0)

我已经使用了您的代码(对日志文件路径进行了一些小的更改,从D:/tmp//tmp/)。它按预期工作。

这意味着,您在此提供的内容是正确的。问题是由其他原因引起的。

鉴于您可以在控制台中看到您的日志消息,很可能是未读取logback-test.xml。在类路径中有logback.groovy,或者您的logback-test.xml在类路径中都不存在。

请提供系统属性logback.debug=true(例如,通过-Dlogback.debug=true)并检查由Logback打印的控制台中的消息,以确定您的问题

答案 1 :(得分:-1)

这个logback.xml文件可以帮助你:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOG_PATH" value="/tmp/name.log" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/debug.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_PATH}/archived/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <appender name="FILE-ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/error.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_PATH}/archived/error.%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <logger name="org.springframework" level="INFO" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE-AUDIT" />
    </logger>

    <logger name="com.yourapp" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE-AUDIT" />
    </logger>

    <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE-AUDIT" />
    </logger>

    <logger name="org.hibernate.SQL" level="TRACE" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE-AUDIT" />
    </logger>

    <root level="error">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE-ERROR" />
    </root>

</configuration>

答案 2 :(得分:-1)

你可以尝试下面的log xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<property name="DEV_HOME" value="c:/logs" />
<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">

    <discriminator>
        <key>logName</key>
        <defaultValue>test</defaultValue>
    </discriminator>
    <sift>
        <appender name="FILE-${logName}" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>D:/tmp/${logName}.log</file>
            <append>false</append>
            <encoder  class="ch.qos.logback.classic.PatternLayout">
                <pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern>
            </encoder>
            <rollingPolicy
              class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
              <FileNamePattern>${DEV_HOME}/${logName}.%i.log.zip
              </FileNamePattern>
              <MinIndex>1</MinIndex>
              <MaxIndex>10</MaxIndex>
        </rollingPolicy>
        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
        </appender>
    </sift>
</appender>

<root level="ALL">
    <appender-ref ref="FILE" />
</root>
</configuration>