自定义日志输出格式

2020-02-26  本文已影响0人  勤劳的杯子
<!--4定义输出格式-->
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <!--<pattern>%d [%thread] %-5level %logger{36} [%file : %line] - %msg%n</pattern>-->
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<!--            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} [%line] - %msg%n</pattern>-->
            <layout class="com.sdworan.xxk.common.config.LoggingLayoutConfig" />
        </encoder>
package com.abc.xxk.common.config;//

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.LayoutBase;
import com.abc.xxk.common.utils.UUIDUtils;
import com.abc.xxk.common.utils.thread.ThreadLocalUtil;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.UUID;

public class LoggingLayoutConfig extends LayoutBase<ILoggingEvent> {

    private static final String space = " ";
    private static final String enter = "\r\n";

    @Override
    public String doLayout(ILoggingEvent event) {
        StringBuilder sb = new StringBuilder();
        if (null != event && null != event.getMDCPropertyMap()) {
            if (ThreadLocalUtil.getUid() == null) {
                ThreadLocalUtil.setUid(UUIDUtils.generateUUID());
            }
            //2020-02-26 11:39:28.015 [http-nio-8001-exec-3] INFO  c.sdworan.xxk.common.interceptor.CommonInterceptor [50] - /shiro/authenticationError;JSESSIONID=f277d4a62b9344ac918ab32340b29a0e: 进入的时间:2020-02-26 11:39:28
            String nowDate = DateTimeFormatter.ofPattern(CoreConstants.ISO8601_PATTERN).format(LocalDateTime.now());

            sb.append(CoreConstants.CURLY_LEFT);
            sb.append("workOrder");
            sb.append(CoreConstants.DASH_CHAR);
            sb.append(nowDate);
            sb.append(CoreConstants.DASH_CHAR);
            sb.append(ThreadLocalUtil.getUid());
            sb.append(CoreConstants.CURLY_RIGHT);
            sb.append(space);
            sb.append("[");
            sb.append(event.getThreadName());
            sb.append("]");
            sb.append(space);
            sb.append(event.getLevel());
            sb.append(space);
            sb.append(event.getLoggerName());
            sb.append(space);
            sb.append(CoreConstants.DASH_CHAR);
            sb.append(space);
            sb.append(event.getFormattedMessage());
            sb.append(enter);
        }

        return sb.toString();
    }
}

参照 http://logback.qos.ch/manual/layouts.html#conversionWord

上一篇 下一篇

猜你喜欢

热点阅读