logback设置自定义字段

配置文件

logback_spring.xml

<appender name="myAppender"  class="ch.qos.logback.core.ConsoleAppender">
    <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
        <includeCallerInfo>false</includeCallerInfo>
        <includeMdc>false</includeMdc>
        <includeContext>false</includeContext>
        <fieldNames>
            <timestamp>time</timestamp>
            <message>info</message>
            <version>[ignore]</version>
            <logger>[ignore]</logger>
            <thread>[ignore]</thread>
            <levelValue>[ignore]</levelValue>
        </fieldNames>
    </encoder>
</appender>
<logger name="pw.fyn.test" additivity="false">
    <appender-ref ref="myAppender"/>
</logger>
  • encoder
    • includeCallerInfo:是否包含调用信息
    • includeMdc:是否包含mdc信息,如果填true,则每一个字段都会在输出的json中出现
    • includeContext:是否包含上下分,如果填true,每一个<springProperty scope="context" />都会输在json中
    • fieldNames:默认字段的映射关系,比如把@timestamp改为了time,忽略掉versionthread等四个字段
  • logger
    • name:受影响的包或类
    • additivity:填false后将不会再输出到默认的root中
    • appender-ref:关联appender

写日志的代码

Printer.java

package pw.fyn.test;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.marker.Markers;
import org.slf4j.Marker;


@Slf4j
public class Printer {

    public void print() {
        LogData data = new LogData();
        Marker marker = Markers.append("data", data);
        log.info(marker, "test info");
    }

    @Data
    private static class LogData {
        private int version = 3;
        private String topic = "order.create";
        private String message_id = "00000000-0000-0000-0000-000000000000";
    }

}

需要额外增加的字段需要通过Marker的方式放到info、error等发方法的第一行

发表评论

电子邮件地址不会被公开。 必填项已用*标注