如何在运行时将PatternLayout添加到根记录器?

时间:2016-02-07 10:50:42

标签: java logging logback

我使用logback作为Slf4j的后端。目前,我使用logback.xml文件配置记录器。我的问题是正在记录敏感信息(我无法控制),我想掩盖这些敏感信息。为了掩盖这些信息,我编写了一个自定义的PatternLayout类,基本上是这样做的:

@Override
public String doLayout(ILoggingEvent event) {
    String message = super.doLayout(event);
    Matcher matcher = sesnsitiveInfoPattern.matcher(message);
    if (matcher.find()) {
        message = matcher.replaceAll("XXX");
    }
    return message;
}

我的问题是我需要告诉logback使用这个自定义模式布局。但是,我不想将其添加到XML配置中。我目前的配置如下:

<configuration> 
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
    <encoder>
      <layout class="com.my.MaskingPatternLayout"> <!-- here -->
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </layout>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

在XML中,我想要的配置看起来像这样(但我不想使用XML):

1 个答案:

答案 0 :(得分:1)

Hello Max我希望您使用的是Log4j 2.x,因为此解决方案使用log4j 2.x中引入的插件方法。首先,你应该创建一个包,你将把你的插件类放在那里,然后你把这两个类放在那里:

my.log4j.pluggins.CustomConfigurationFactory:

@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
    @Order(value = 0)
    public class CustomConfigurationFactory extends ConfigurationFactory {

        private Configuration createConfiguration(final String name,
                ConfigurationBuilder<BuiltConfiguration> builder) {
            System.out.println("init logger");
            builder.setConfigurationName(name);
            builder.setStatusLevel(Level.INFO);
            builder.setPackages("my.log4j.pluggins");
            AppenderComponentBuilder appenderBuilder = builder.newAppender(
                    "Stdout", "CONSOLE").addAttribute("target",
                    ConsoleAppender.Target.SYSTEM_OUT);
            appenderBuilder
                    .add(builder
                            .newLayout("PatternLayout")
                            .addAttribute("pattern", "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %myMsg%n"));
            builder.add(appenderBuilder);
            builder.add(builder.newRootLogger(Level.TRACE).add(
                    builder.newAppenderRef("Stdout")));
            return builder.build();
        }

        @Override
        protected String[] getSupportedTypes() {
            String[] supportedExt = { "*" };
            return supportedExt;

        }

        @Override
        public Configuration getConfiguration(ConfigurationSource source) {
            ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
            return createConfiguration(source.toString(), builder);
        }

        @Override
        public Configuration getConfiguration(String name, URI configLocation) {
            ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
            return createConfiguration(name, builder);
        }

    }

my.log4j.pluggins.SampleLayout:

    @Plugin(name = "CustomConverter", category = "Converter")
    @ConverterKeys({"myMsg"})
    public class SampleLayout extends LogEventPatternConverter {

        protected SampleLayout(String name, String style) {
            super(name, style);
        }
        public static SampleLayout newInstance(){
            return new SampleLayout("custConv", "custConv");
        }

        @Override
        public void format(LogEvent event, StringBuilder stringBuilder) {
           //replace the %myMsg by XXXXX if sensitive           
           if (sensitive()){
               stringBuilder.append("XXXX");}
           else {
            stringBuilder.append(event.getMessage().getFormattedMessage());}            
        }   
    }

CustomConfiguration类负责创建log4j的配置和第9行,其中&#39; builder.setPackages(&#34; my.log4j.pluggins&#34;)&#39;对于扫描该软件包并获取SampleLayout的转换器插件非常重要。 第二课将负责格式化新密钥&#39;%myMsg&#39;在包含我的敏感消息的模式中,此Converter类检查该消息是否敏感并相应地进行操作。

在开始记录之前,您应该像这样配置log4j

ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory());