package ru.yandex.qe.dispenser.metrics;


import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.UnsynchronizedAppenderBase;

import ru.yandex.monlib.metrics.labels.Labels;
import ru.yandex.monlib.metrics.primitives.Rate;
import ru.yandex.monlib.metrics.registry.MetricRegistry;

public class InstrumentedAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private final Rate all;
    private final Rate trace;
    private final Rate debug;
    private final Rate info;
    private final Rate warn;
    private final Rate error;

    public InstrumentedAppender(MetricRegistry metricRegistry) {
        setName(Appender.class.getName());
        this.all = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "all"));
        this.trace = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "trace"));
        this.debug = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "debug"));
        this.info = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "info"));
        this.warn = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "warn"));
        this.error = metricRegistry.rate("logback.event_rate", Labels.of("event_type", "error"));
    }

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

    @Override
    protected void append(ILoggingEvent event) {
        all.inc();
        switch (event.getLevel().toInt()) {
            case Level.TRACE_INT:
                trace.inc();
                break;
            case Level.DEBUG_INT:
                debug.inc();
                break;
            case Level.INFO_INT:
                info.inc();
                break;
            case Level.WARN_INT:
                warn.inc();
                break;
            case Level.ERROR_INT:
                error.inc();
                break;
            default:
                break;
        }
    }

}
