package ru.yandex.qe.dispenser.metrics;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.status.InfoStatus;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.qe.dispenser.solomon.SolomonHolder;

@Component
public class LogbackMetrics {

    @Value("${logging.telemetry.enabled:true}")
    private boolean enabled;

    @Inject
    private SolomonHolder solomonHolder;

    @PostConstruct
    public void init() {
        if (enabled) {
            LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
            Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
            InstrumentedAppender metricsAppender = new InstrumentedAppender(solomonHolder.getRootRegistry());
            metricsAppender.setContext(root.getLoggerContext());
            metricsAppender.start();
            root.addAppender(metricsAppender);
            factory.getStatusManager().add(new InfoStatus(String.format("attach telemetry appender %s to %s logger",
                    metricsAppender.getName(), root.getName()), this));
            factory.getStatusManager().add(new LogbackDropListener(solomonHolder.getRootRegistry()));
        }
    }

}
