package cn.reghao.tnb.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.reghao.jutil.jdk.result.AppLog;
import cn.reghao.tnb.log.ws.WsClient;

/**
 * @author reghao
 * @date 2023-06-03 19:37:21
 */
public class WsAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    private final String app;
    private final String host;
    private final WsClient wsClient;

    public WsAppender(String url, String app, String host) {
        this.app = app;
        this.host = host;
        this.wsClient = new WsClient(url);
        setName("wsAppender");
    }

    @Override
    public void start() {
        wsClient.connect();
        super.start();
    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    protected void append(ILoggingEvent event) {
        AppLog appLog = getAppLog(event);
        wsClient.send(appLog);
    }

    private AppLog getAppLog(ILoggingEvent event) {
        long timestamp = event.getTimeStamp();
        String level = event.getLevel().toString();
        String thread = event.getThreadName();
        String logger = event.getLoggerName();
        String message = event.getFormattedMessage();
        return new AppLog(app, host, timestamp, level, thread, logger, message);
    }
}
