com.lwq.fast.log.fastlogclient.logback.appender.RabbitMqAppender Maven / Gradle / Ivy
The newest version!
package com.lwq.fast.log.fastlogclient.logback.appender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lwq.fast.log.fastlogclient.logback.appender.util.MessageUtil;
import com.lwq.fast.log.fastlogcore.client.rabbitmq.RabbitMqClient;
import com.lwq.fast.log.fastlogcore.entity.Message;
import com.lwq.fast.log.fastlogcore.util.ThreadPoolUtil;
import com.lwq.fast.log.fastlogcore.work.MessageCollection;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 自定义 appender 使用rabbitmq 来收集日志
*
* @author 刘文强
*/
public class RabbitMqAppender extends AppenderBase {
/**
* 应用名称
*/
private String appName;
/**
* 环境信息 如: dev, test, prod 等
*/
private String env;
private String host;
private int port;
private String virtualHost;
private String username;
private String password;
@Override
protected void append(ILoggingEvent iLoggingEvent) {
// 讲消息放入队列暂存
Message message = MessageUtil.formatMessage(appName, env, iLoggingEvent);
if (ObjectUtil.isNotNull(message)) {
MessageCollection.addMessage2Queue(JSON.toJSONString(message));
}
}
@Override
public void stop() {
super.stop();
}
@Override
public void start() {
super.start();
//初始化
RabbitMqClient instance = RabbitMqClient.getInstance(host, port, virtualHost, username, password);
if (ObjectUtil.isNotNull(instance)){
// 从队列中获取消息,发送到 MQ中
ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.getThreadPoolExecutor();
threadPoolExecutor.execute(() -> {
MessageCollection.messageCollect(instance);
});
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getVirtualHost() {
return virtualHost;
}
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
}