logger.py 1.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
"""Event tracker backend that saves events to a python logger."""

from __future__ import absolute_import

import logging
import json

from django.conf import settings

from track.backends import BaseBackend
11
from track.utils import DateTimeJSONEncoder
12 13

log = logging.getLogger('track.backends.logger')
14
application_log = logging.getLogger('track.backends.application_log')  # pylint: disable=invalid-name
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36


class LoggerBackend(BaseBackend):
    """Event tracker backend that uses a python logger.

    Events are logged to the INFO level as JSON strings.

    """

    def __init__(self, name, **kwargs):
        """Event tracker backend that uses a python logger.

        :Parameters:
          - `name`: identifier of the logger, which should have
            been configured using the default python mechanisms.

        """
        super(LoggerBackend, self).__init__(**kwargs)

        self.event_logger = logging.getLogger(name)

    def send(self, event):
37 38 39 40
        try:
            event_str = json.dumps(event, cls=DateTimeJSONEncoder)
        except UnicodeDecodeError:
            application_log.exception(
41
                "UnicodeDecodeError Event_data: %r", event
42
            )
43
            raise
44 45 46 47 48 49 50

        # TODO: remove trucation of the serialized event, either at a
        # higher level during the emittion of the event, or by
        # providing warnings when the events exceed certain size.
        event_str = event_str[:settings.TRACK_MAX_EVENT]

        self.event_logger.info(event_str)