import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.ThrowableProxy; import ch.qos.logback.core.Layout; import ch.qos.logback.core.UnsynchronizedAppenderBase; import com.alibaba.fastjson.JSONObject; import com.xiaoleilu.hutool.exceptions.ExceptionUtil; import com.xiaoleilu.hutool.system.SystemUtil; import lombok.Getter; import lombok.Setter; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate;
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
@Getter @Setter public class LogbackMQAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private CachingConnectionFactory connectionFactory = null; private RabbitTemplate template;
String appName;
String host;
int port;
String username;
String password;
Layout<ILoggingEvent> layout;
@Override public void start() { if (layout == null) { addWarn("Layout was not defined"); } connectionFactory = new CachingConnectionFactory(host, port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); template = new RabbitTemplate(connectionFactory); super.start(); }
@Override public void stop() { if (!isStarted()) { return; } template.destroy(); connectionFactory.destroy(); super.stop(); }
@Override protected void append(ILoggingEvent event) { if (event == null || !isStarted()) { return; } RequestLog requestLog = new RequestLog();
requestLog.setHost(SystemUtil.getHostInfo().getAddress()); requestLog.setMachineName(SystemUtil.getHostInfo().getName()); requestLog.setApplicationName(appName); requestLog.setAddTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z", Locale.CHINESE).format(new Date())); if (event.getLevel().levelInt == Level.ERROR_INT) { final IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy == null) { return; } if (!(throwableProxy instanceof ThrowableProxy)) { return; }
Throwable throwable = ((ThrowableProxy) throwableProxy).getThrowable(); requestLog.setMessage(event.getFormattedMessage() + ",\n\n详细错误信息如下\n" + ExceptionUtil.stacktraceToString(throwable)); requestLog.setLogLevel(LogLevel.ERROR.ordinal()); requestLog.setStatusCode(500); template.convertAndSend(QueueConsts.QUEUE_ERROR_NAME, JSONObject.toJSONString(requestLog)); } else { requestLog.setMessage(event.getFormattedMessage()); requestLog.setLogLevel(LogLevel.INFORMATION.ordinal()); requestLog.setStatusCode(200); template.convertAndSend(QueueConsts.QUEUE_INFO_NAME, JSONObject.toJSONString(requestLog)); } } }
|