package cn.reghao.devops.web.mgr.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.reghao.devops.web.ws.handler.LogHandler;
import cn.reghao.jutil.jdk.converter.DateTimeConverter;
import cn.reghao.jutil.jdk.result.AppLog;

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

    public PushAppender(String app, String host, LogHandler logHandler) {
        this.app = app;
        this.host = host;
        this.logHandler = logHandler;
        setName("pushAppender");
    }

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

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

    @Override
    protected void append(ILoggingEvent event) {
        AppLog appLog = getAppLog(event);
        logHandler.pushAppLog(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();
        AppLog appLog = new AppLog(app, host, timestamp, level, thread, logger, message);
        appLog.setDateTimeStr(DateTimeConverter.format(timestamp));
        return appLog;
    }
}
