Slf4j+logback实现JSON格式日志输出方式
程序员文章站
2022-06-23 10:44:06
目录slf4j+logback实现json格式日志输出依赖logback 记录json日志slf4j+logback实现json格式日志输出依赖
slf4j+logback实现json格式日志输出
依赖
<dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <version>1.18.8</version> <scope>provided</scope> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.28</version> </dependency> <dependency> <groupid>net.logstash.logback</groupid> <artifactid>logstash-logback-encoder</artifactid> <version>6.1</version> </dependency> <dependency> <groupid>ch.qos.logback</groupid> <artifactid>logback-classic</artifactid> <version>1.2.3</version> </dependency> <dependency> <groupid>ch.qos.logback</groupid> <artifactid>logback-access</artifactid> <version>1.2.3</version> </dependency>
logback.xml
<encoder class="net.logstash.logback.encoder.loggingeventcompositejsonencoder"> <providers class="net.logstash.logback.composite.loggingevent.loggingeventjsonproviders"> <pattern> <pattern> { "date":"%date{\"yyyy-mm-dd hh:mm:ss.sss\",utc}", "level":"%level", "msg":"%msg" } </pattern> </pattern> </providers> <charset>utf-8</charset> </encoder>
输出:
{"date":"2019-09-17 08:29:20.879","level":"info","msg":"{\"tags\":{\"namespace\":\"service.mqtt.push\",,\"metric.correct\":true}}"}
{"date":"2019-09-17 08:30:20.784","level":"info","msg":"{\"tags\":{\"namespace\":\"service.mqtt.command\",\"metric.correct\":true}}"}
{"date":"2019-09-17 08:30:20.854","level":"info","msg":"{\"tags\":{\"namespace\":\"service.mqtt.push\",\"metric.correct\":true}}"}
logback 记录json日志
首先在你要记录的json日志中需要对某个类单独配置他的logger
如图
然后在你对应的类中调用 该logger
如图
然后在这里你需要记录的位置记录你需要的json 数据 这里的javaben tostring方法已经重写了,返回的的字符串是json字符串
// 此处添加操作日志记录 es_log.info(new inoutlogmodel(outboundparamsmodel.getscancode(), outboundresult.getformcode(), outboundparamsmodel.getmerchantid() + "", outboundparamsmodel.getsource(), "此处在逐单出库!", new simpledateformat("yyyy-mm-dd hh:mm:ss").format(new date()), outboundparamsmodel.getuserinfo()) .tostring());
最后在服务器上查看刚才所记录的日志如图
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
上一篇: 小米12定价如超4000将难获消费者接受