package cn.reghao.autodop.dmaster.util.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.reghao.autodop.common.msg.pub.dto.node.constant.AppId;
import cn.reghao.autodop.dmaster.machine.db.crud.NodeLogCrud;
import cn.reghao.autodop.dmaster.machine.model.po.NodeLog;
import cn.reghao.jdkutil.machine.MachineId;

/**
 * @author reghao
 * @date 2021-06-08 19:37:21
 */
public class MongoAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    private final String appId;
    private final NodeLogCrud nodeLogCrud;
    
    public MongoAppender(NodeLogCrud nodeLogCrud) {
        this.appId = AppId.dmaster.name();
        this.nodeLogCrud = nodeLogCrud;
    }

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

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

    @Override
    protected void append(ILoggingEvent event) {
        NodeLog nodeLog = nodeLog(event);
        nodeLogCrud.save(nodeLog);
    }

    private NodeLog nodeLog(ILoggingEvent event) {
        NodeLog machineNodeLog = new NodeLog();
        machineNodeLog.setMachineId(MachineId.id());
        machineNodeLog.setAppId(appId);
        machineNodeLog.setTimestamp(event.getTimeStamp());
        machineNodeLog.setLevel(event.getLevel().toString());
        machineNodeLog.setThreadName(event.getThreadName());
        machineNodeLog.setLoggerName(event.getLoggerName());
        machineNodeLog.setMessage(event.getFormattedMessage());
        return machineNodeLog;
    }
}
