当前位置:主页 > 软件编程 > JAVA代码 >

Slf4j+logback实现JSON格式日志输出方式

时间:2022-10-25 09:32:58 | 栏目:JAVA代码 | 点击:

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());

最后在服务器上查看刚才所记录的日志如图

您可能感兴趣的文章:

相关文章