java Spring下如何配置Logback

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32023060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:30:52  来源:igfitidea点击:

How to configure Logback under Spring

javaspringlogback

提问by Aleksandr Dubinsky

Most of the examples for configuring Logback use logback.xml. However, my application uses Spring features of profilesand PropertySourcesPlaceholderConfigurerto inject environment-specific configuration into components that need it. What is the right way to configure Logback in a programmatic way just like my other Spring components?

大多数配置 Logback 的示例使用 logback.xml。但是,我的应用程序使用配置文件PropertySourcesPlaceholderConfigurer 的Spring 功能将特定于环境的配置注入需要它的组件中。就像我的其他 Spring 组件一样,以编程方式配置 Logback 的正确方法是什么?

回答by Aleksandr Dubinsky

As orid pointed out, the official way to use Logback in Spring is with the Logback Spring extension.

正如 orid 指出的那样,在 Spring 中使用 Logback 的官方方法是使用Logback Spring 扩展

The really cool thing is that the Logback Spring extension starts before Spring or the servlet and stores log messages until the Appenders are configured. (Simple appenders will be available immediately, while those that need Spring are proxied through DelegatingLogbackAppender).

真正酷的是 Logback Spring 扩展在 Spring 或 servlet 之前启动并存储日志消息,直到配置了 Appender。(简单的 appender 将立即可用,而那些需要 Spring 的则通过 代理DelegatingLogbackAppender)。

In addition it allows you to:

此外,它还允许您:

  • Use SLF4J's java.util.logging bridge.
  • Specify the logback.xmllocation using a Spring resource pathand system propertyplaceholders.
  • Use the pre-set system property webapp.root(path to unpacked WAR directory) inside the logback.xmlfor setting log file paths, etc.
  • 使用 SLF4J 的 java.util.logging 桥接器。
  • logback.xml使用 Spring资源路径系统属性占位符指定位置。
  • 使用里面预先设置的系统属性webapp.root(解压后的 WAR 目录的路径)logback.xml来设置日志文件路径等。

回答by Sanjay

In one of our projects, we had coded it like this:

在我们的一个项目中,我们是这样编码的:

import java.io.IOException;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

@Component
public class InitializationService implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${logbackErrorMailPassword}")
    private String logbackErrorMailPassword;

    @Value("${supportEmail}")
    private String supportEmail;

    @Value("${spring.profiles.active}")
    private String env;

    @Value("${log.dir}")
    private String logDir;

    @Value("${log.name}")
    private String logName;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        try {
            configureLogback();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void configureLogback() throws IOException {

        // assume SLF4J is bound to logback in the current environment
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator jc = new JoranConfigurator();
            jc.setContext(context);
            context.reset(); // override default configuration
            // inject the name of the current application as "application-name"
            // property of the LoggerContext
            context.putProperty("LOG_DIR", logDir);
            context.putProperty("LOG_NAME", logName);

            context.putProperty("ERROR_MAIL_PASSWORD", logbackErrorMailPassword);
            context.putProperty("SUPPORT_EMAIL_ID", supportEmail);
            context.putProperty("ENV", env);
            //jc .doConfigure(servletContext.getRealPath("/WEB-INF/my-logback.xml"));
            jc.doConfigure(new ClassPathResource("my-logback.xml").getInputStream());
        } catch (JoranException je) {
              // StatusPrinter will handle this
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);

    }
}

my-logback.xmlwas residing at src/main/resources, looking like this:

my-logback.xml住在src/main/resources,看起来像这样:

<configuration debug="true" scan="true" scanPeriod="10 minutes"> 
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%date %level [%thread] %logger %msg%n</Pattern>
        </encoder>
    </appender>
    <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${LOG_DIR}${LOG_NAME}.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <FileNamePattern>
           ${LOG_DIR}${LOG_NAME}-%d.%i.log.gz
          </FileNamePattern>
          <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <MaxFileSize>10MB</MaxFileSize>
          </TimeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
          <Pattern>%date %level [%thread] %logger %msg%n</Pattern>
        </encoder>
    </appender>
    <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- deny all events with a level below ERROR -->
            <level>ERROR</level>
        </filter>

        <smtpHost>xxxxxx.bluehost.com</smtpHost>
        <smtpPort>465</smtpPort>
        <username>xxxxxxx+xxxxx.com</username>
        <password>${ERROR_MAIL_PASSWORD}</password>
        <SSL>true</SSL>

        <to>${SUPPORT_EMAIL_ID}</to>
        <!-- Multiple to elements are permitted -->

        <from>[email protected]</from>
        <subject>[${ENV}] ERROR in ${LOG_NAME}</subject>
        <cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
              <bufferSize>1</bufferSize>
        </cyclicBufferTracker>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date %-5level %logger{35} - %message%n</pattern>
        </layout>
    </appender>
    <logger name="javax.net" level="info"/>
    <logger name="javax.management" level="info"/>
    <logger name="org.springframework" level="info"/>
    <logger name="org.compass" level="info"/>
    <logger name="org.tuckey" level="info"/>
    <root level="info">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="ROLLING" />
        <appender-ref ref="EMAIL" />
    </root>

</configuration>