MDC更改未选中,但在带有引导的Spring Boot应用中

时间:2019-06-26 12:20:13

标签: java logback slf4j mdc spring-logback

我需要动态配置日志位置,因此我在logback.xml

中创建了 SiftingAppender
 <appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
            <key>userRole</key>
            <defaultValue>ANONYMOUS</defaultValue>
        </discriminator>
        <sift>
            <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
                <file>${userRole}.log</file>
                <encoder
                        class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                    <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
                </encoder>
            </appender>
        </sift>
  </appender>

现在我需要动态更改userRole,以便可以选择更改。

 MDC.put("userRole","priyamal");

但是更改不会在spring boot应用程序中选择,但是如果我们以编程方式更改日志文件,则会添加新的更改,这就是我以编程方式进行的操作

 static void programmaticConfiguration() {
                 // Configure logback
                  LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
                  loggerContext.reset();
                  PatternLayoutEncoder layout = new PatternLayoutEncoder();
                  layout.setContext(loggerContext);
                  layout.setPattern("%X{first} %X{last} - %m%n");
                  layout.start();
                  ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
                  appender.setContext(loggerContext);
                  appender.setEncoder(layout);
                  appender.start();
                  // cast root logger to c.q.logback.classic.Logger so that we can attach
                  // an appender to it
                  ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("root");
                  root.addAppender(appender);
              }

我已在logback.xml文件中启用<configuration scan="true">,甚至尝试调用此功能,该功能将根据文档配置xml文件 https://logback.qos.ch/xref/chapters/mdc/SimpleMDC.html

static void XMlConfig(){
        try {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        loggerContext.reset();
        configurator.doConfigure(ResourceUtils.getFile("classpath:logback.xml"));
        } catch (JoranException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

但没有任何作用,我是否缺少任何东西?任何帮助将不胜感激。

0 个答案:

没有答案