<commit_before>import logging

import markus
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from markus.backends import BackendBase


logger = logging.getLogger(__name__)


def register():
    backends = []

    if settings.METRICS_USE_DEBUG_LOGS:
        backends.append({"class": "normandy.base.metrics.DebugLogsBackend"})

    if settings.METRICS_USE_STATSD:
        backends.append(
            {
                "class": "markus.backends.datadog.DatadogMetrics",
                "options": {
                    "statsd_host": settings.METRICS_STATSD_HOST,
                    "statsd_port": settings.METRICS_STATSD_PORT,
                    "statsd_namespace": settings.METRICS_STATSD_NAMESPACE,
                },
            }
        )

    markus.configure(backends=backends)


class DebugLogsBackend(BackendBase):
    def __init__(self, options):
        if not settings.DEBUG:
            raise ImproperlyConfigured(
                f"The {self.__class__.__name} can only be used if DEBUG=True"
            )

    def _emit(self, type, stat, value, tags, *, op="="):
        # round floats to 2 decimal points
        if isinstance(value, float):
            if int(value) != value:
                value = round(value * 100.0) / 100.0

        result = f"[{type}] {stat} {op} {value}"
        if tags:
            tags_display = ", ".join(t for t in tags)
            result += f" tags=[{tags_display}]"
        logger.debug(result)

    def incr(self, stat, value, tags=None):
        op = "+=" if value >= 0 else "-="
        self._emit("incr", stat, value, tags, op=op)

    def gauge(self, stat, value, tags=None):
        self._emit("gauge", stat, value, tags)

    def timing(self, stat, value, tags=None):
        self._emit("timing", stat, f"{value:>.1f}ms", tags)

    def histogram(self, stat, value, tags=None):
        self._emit("histogram", stat, value, tags)<commit_msg>Port to Markus 2.0<commit_after>import logging

import markus
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from markus.backends import BackendBase


logger = logging.getLogger(__name__)


def register():
    backends = []

    if settings.METRICS_USE_DEBUG_LOGS:
        backends.append({"class": "normandy.base.metrics.DebugLogsBackend"})

    if settings.METRICS_USE_STATSD:
        backends.append(
            {
                "class": "markus.backends.datadog.DatadogMetrics",
                "options": {
                    "statsd_host": settings.METRICS_STATSD_HOST,
                    "statsd_port": settings.METRICS_STATSD_PORT,
                    "statsd_namespace": settings.METRICS_STATSD_NAMESPACE,
                },
            }
        )

    markus.configure(backends=backends)


class DebugLogsBackend(BackendBase):
    def __init__(self, options):
        super().__init__(options)
        if not settings.DEBUG:
            raise ImproperlyConfigured(
                f"The {self.__class__.__name} can only be used if DEBUG=True"
            )

    def emit(self, record):
        # round floats to 2 decimal points
        value = record.value
        if record.stat_type == "timing":
            value = f"{value:.1f}ms"

        elif isinstance(value, float):
            if int(value) != value:
                value = round(value * 100.0) / 100.0

        op = "="
        if record.stat_type == "incr":
            op = "+="

        result = f"[{record.stat_type}] {record.key} {op} {record.value}"
        if record.tags:
            tags_display = ", ".join(t for t in record.tags)
            result += f" tags=[{tags_display}]"
        logger.debug(result)
{'fraction_non_alphanumeric': 0.11449551264617895, 'fraction_numerical': 0.006255099265705739, 'mean_word_length': 2.1844155844155844, 'pattern_counts': {'":': 14, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5252667', 'n_tokens_mistral': 1140, 'n_tokens_neox': 1083, 'n_words': 245}