package ru.yandex.qe.dispenser.metrics;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import ru.yandex.monlib.metrics.labels.Labels;
import ru.yandex.monlib.metrics.primitives.Rate;
import ru.yandex.qe.dispenser.solomon.SolomonHolder;

@Component
public class UncaughtExceptionMetrics {

    public static final Logger LOG = LoggerFactory.getLogger(UncaughtExceptionMetrics.class);

    @Inject
    private SolomonHolder solomonHolder;

    @PostConstruct
    public void init() {
        Rate uncaughtExceptionsRate = solomonHolder.getRootRegistry()
                .rate("threads.uncaught_exceptions_rate", Labels.of());
        Thread.UncaughtExceptionHandler delegateExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            uncaughtExceptionsRate.inc();
            LOG.error("Uncaught exception in thread " + t, e);
            if (delegateExceptionHandler != null) {
                delegateExceptionHandler.uncaughtException(t, e);
            }
        });
    }

}
