How to Write Dropwizard Custom Appender?

Dropwizard是一个用于构建高性能、操作友好的RESTful Web服务的Java框架。它集成了Jackson、Logback和slf4j,方便输出JSON日志。官方文档提供了配置config.yml使日志格式为JSON的示例。然而,当需要自定义JSON日志键时,可以通过继承AbstractAppenderFactory并覆盖build()方法来创建自己的Appender。可以扩展JsonLayout并覆盖toJsonMap()和addCustomDataToJsonMap()方法以进行自定义。如果需要更多定制,可以扩展JsonFormatter创建JacksonJsonFormatter。在src/main/resources/META-INF/services下创建文件"io.dropwizard.logging.AppenderFactory",并在其中添加自定义Appender类名。最后,在config.yml中使用自定义Appender。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dropwizard is a is a Java framework for developing ops-friendly, high-performance, RESTful web services. It is internally integrate Jaskson, and Logback and slf4j, so that it is easy to output JSON logs for the application that created based on Dropwizard.

In the official document, it provides a sample about how to configure the config.yml to make the log format to JSON.

Below is an example to configure the JSON log

server:
  applicationConnectors:
    - type: http
      port: 9080
  adminConnectors:
    - type: http
      port: 9081

logging:
  level: INFO
  loggers:
      my.example.nccsdropwizard: DEBUG
  appenders:
    - type: console
      layout:
        type: json
        timestampFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        prettyPrint: false
        appendLineSeparator: true
        includes: [timestamp, threadName, level, loggerName, message, mdc, exception]
        customFieldNames:
            timestamp: "time"
            message: "msg"
        additionalFields:
            service-name: "user-service"
        includesMdcKeys: [userId]
        flattenMdc: true
        exception:
            rootFirst: true
            depth: full
            evaluators: [org.apache]

However, there may be the case that that you want to customize the output JSON log keys like introduce the new key for each log, here is the way how to write your own appender?

  • Extends AbstractAppenderFactory class, and override the build() function, inside this function, you could try to use your own JsonLayout class, or your own JaksonJSONFromatter if you need.
  • package my.example.Log;
    
    impo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值