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

最後在服務器上查看剛才所記錄的日志如圖

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: