直接源码
package com.qds.phoenix.foundation.common.log;
import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.LayoutBase;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class QdsLogLayout extends LayoutBase<ILoggingEvent> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH点mm分ss秒SSS");
private final String L = "[";
private final String R = "]";
private final ExtendedThrowableProxyConverter throwableConverter = new ExtendedThrowableProxyConverter();
public QdsLogLayout() {
throwableConverter.start();
}
@Override
public String doLayout(ILoggingEvent event) {
JSONObject object = new JSONObject(2);
String levelStr = event.getLevel().levelStr;
object.put("level", levelStr);
String loggerName = getMethod(event);
object.put("class", loggerName);
String format = Instant.ofEpochMilli(event.getTimeStamp()).atZone(ZoneId.systemDefault()).format(formatter);
object.put("date", format);
StringBuilder sb = new StringBuilder();
sb.append(format)
.append(StringUtils.SPACE)
.append(levelStr)
.append(StringUtils.SPACE)
.append(L)
.append(event.getThreadName())
.append(R)
.append(StringUtils.SPACE)
.append(loggerName)
.append(StringUtils.SPACE)
.append(event.getFormattedMessage());
if (event.getThrowableProxy() != null) {
sb.append(CoreConstants.LINE_SEPARATOR)
.append(throwableConverter.convert(event));
}
object.put("message", sb.toString());
return object.toJSONString().concat(CoreConstants.LINE_SEPARATOR);
}
/**
* 获取打印日志方法
*
* @param event
* @return
*/
private String getMethod(ILoggingEvent event) {
StringBuilder sb = new StringBuilder(64);
sb.append(event.getLoggerName())
.append(CoreConstants.DOT);
StackTraceElement[] cda = event.getCallerData();
if (cda != null && cda.length > 0) {
StackTraceElement element = cda[0];
sb.append(element.getMethodName())
.append(CoreConstants.COLON_CHAR)
.append(element.getLineNumber());
} else {
sb.append(CallerData.NA);
}
return sb.toString();
}
}