【问题标题】:Log different levels in different files using Dropwizard使用 Dropwizard 在不同文件中记录不同级别
【发布时间】:2020-09-28 11:31:11
【问题描述】:

该问题类似于 - How to configure log4j to log different log levels to different files for the same logger 下所述的问题。我可以在这里找到的现有问题主要是处理 logback 和 log4j 配置。专门在 Dropwizard 配置中寻找解决此问题的方法。

已尝试通过 Internet 环顾四周,似乎 LevelMatchFilter 可能适合使用,但无法弄清楚 Dropwizard 周围的文档。

我目前拥有的是

logging:
  level: INFO
  appenders:
    - type: file
      threshold: INFO
      logFormat: '%date{dd-MM-yyyy HH:mm:ss.SSS} %X{X-Request-Id} [%thread] %-5level %logger{36} - %msg%n'
      currentLogFilename: .../info.log
      archivedLogFilenamePattern: .../info-%i.log.gz
      archivedFileCount: 2
      timeZone: IST
      maxFileSize: 100MB

    - type: file
      threshold: WARN
      currentLogFilename: .../warn.log
      archivedLogFilenamePattern: .../warn-%i.log.gz
      ... other attributes

    - type: file
      threshold: ERROR
      ...similar attributes for error logs

但这会导致log.error 成为三个文件的一部分,我打算执行的是确保它只是error.log 文件的一部分并与其他文件相关。

【问题讨论】:

    标签: logging dropwizard


    【解决方案1】:

    Dropwizard 有自己的日志配置,它支持adding filters by writing FilterFactory classes

    例如,这里有一个 FilterFactory,它过滤掉除 ERROR 级别日志事件之外的所有内容:

    @JsonTypeName("error-only")
    public class ErrorLogFilter implements FilterFactory<ILoggingEvent> {
    
        @Override
        public Filter<ILoggingEvent> build() {
            return new Filter<ILoggingEvent>() {
                @Override
                public FilterReply decide(ILoggingEvent event) {
                    if (event.getLevel().equals(Level.ERROR)) {
                        return FilterReply.NEUTRAL;
                    } else {
                        return FilterReply.DENY;
                    }
                }
            };
    
        }
    }
    

    要注册一个工厂,它的全限定类名必须列在 META-INF/services/io.dropwizard.logging.filter.FilterFactory 文件中。

    获取文件附加程序之一以使用它的配置如下:

      - type: file
        threshold: ERROR
        logFormat: '%date{dd-MM-yyyy HH:mm:ss.SSS} %X{X-Request-Id} [%thread] %-5level %logger{36} - %msg%n'
        currentLogFilename: .../error.log
        archivedLogFilenamePattern: .../error-%i.log.gz
        archivedFileCount: 2
        timeZone: IST
        maxFileSize: 100MB
        filterFactories:
          - type: error-only 
    

    【讨论】:

    • 感谢您的回答,这看起来很有希望。我还可以进一步将它与我对#filterfactories 的发现联系起来。但是我仍然无法理解通过META-INF 注册它的重要性,介意详细说明那部分吗?另外,没有工厂注册就没有办法在dropwizard中实际翻译#levelFilter
    • 这里是FilterFactory 的来源,它使用Discoverable 来发现子类型。所以这只是注册子类型的内置 Dropwizard 方式。如果您查看 dropwizard-logging 中的代码,这是添加日志过滤器的最简单方法。
    • 您可能对这个问题的答案stackoverflow.com/questions/27483442/… 感兴趣。扩展 FileAppenderFactory 是一种选择,实现单独的记录器也是如此。
    猜你喜欢
    • 2020-12-25
    • 2017-02-02
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多