Example #1
0
 def mapPriority(self, level):
     """Map the priority level to a syslog level """
     return self.levelMap.get(level, SysLogHandler.mapPriority(self, level))
Example #2
0
class JsonLogFormatter(logging.Formatter):
    """
    Log formatter that outputs machine-readable json.

    Adapted from:
    https://github.com/mozilla-services/python-dockerflow/blob/master/src/dockerflow/logging.py
    https://github.com/DanHoerst/json-log-formatter/blob/master/json_log_formatter/__init__.py
    """
    LOGGING_FORMAT_VERSION = "1"

    def __init__(self,
                 fmt=None,
                 datefmt=None,
                 style="%",
                 logger_name="json_logger"):
        parent_init = logging.Formatter.__init__
        parent_init(self, format, datefmt, style)
        self.logger_name = logger_name
        self.hostname = socket.gethostname()
        self.syslog_handler = SysLogHandler()

    def format(self, record):
        """
        Map from Python LogRecord attributes to JSON log format fields

        * usage - logger.info('My message', extra={'something': 'sick. tight.'})
        * from - https://docs.python.org/3/library/logging.html#logrecord-attributes
        * to -
            {
                'message': 'My message',
                'time': '2015-09-01T06:06:26.524448',
                'something': 'sick. tight.'
            }
        """
        data = OrderedDict({
            'logger':
            record.name,
            'level':
            self.syslog_handler.mapPriority(record.levelname),
            'time':
            datetime.utcnow().isoformat(),
        })

        message = record.getMessage()
        # Only include the 'msg' key if it has content and is not already a JSON blob.
        if message and not message.startswith("{") and not message.endswith(
                "}"):
            data["msg"] = message

        data.update({
            'hostname': self.hostname,
        })

        if global_ctx.user:
            data['user_id'] = global_ctx.user.pk
        if global_ctx.remote_addr:
            data['remote_addr'] = global_ctx.remote_addr

        # Include any other custom attributes set on the record.
        data.update({
            attr_name: record.__dict__[attr_name]
            for attr_name in record.__dict__ if attr_name not in BUILTIN_ATTRS
        })

        if global_ctx.trace_id:
            data['trace_id'] = global_ctx.trace_id
        if global_ctx.amzn_trace:
            data['amzn_trace'] = global_ctx.amzn_trace

        # If there is an error, format it for nice output.
        if record.exc_info is not None:
            data["error"] = repr(record.exc_info[1])
            data["traceback"] = safer_format_traceback(*record.exc_info)

        return json.dumps(data, cls=SafeJSONEncoder)
 def mapPriority(self, level):
     """Map the priority level to a syslog level """
     return self.levelMap.get(level, SysLogHandler.mapPriority(self, level))
Example #4
0
class JsonLogFormatter(logging.Formatter):
    """
    :obj:`logging.Formatter` that transforms the logging record into machine
    readable JSON.

    This was adapted from the following projects:

    https://github.com/mozilla-services/python-dockerflow/blob/master/src/dockerflow/logging.py  # noqa
    https://github.com/DanHoerst/json-log-formatter/blob/master/json_log_formatter/__init__.py  # noqa

    Usage:
    -----
    >>> logger = logging.getLogger('greenbudget')
    >>> logger.info("Some message", extra={"foo": "bar", "apple": "banana"})
    >>> {
    >>>   "message": "Some message",
    >>>   "foo": "bar",
    >>>   "apple": "banana",
    >>> }
    """
    LOGGING_FORMAT_VERSION = "1"

    def __init__(self,
                 fmt=None,
                 datefmt=None,
                 style="%",
                 logger_name="greenbudget"):
        logging.Formatter.__init__(self, fmt, datefmt, style)
        self.logger_name = logger_name
        self.hostname = socket.gethostname()
        self.syslog_handler = SysLogHandler()

    def format(self, record):
        data = OrderedDict({
            'logger':
            record.name,
            'level':
            self.syslog_handler.mapPriority(record.levelname),
            'time':
            datetime.utcnow().isoformat(),
        })

        # Only include the `msg` if it has content and is not already a JSON
        # blob.
        message = record.getMessage()
        if (message and not message.startswith("{")
                and not message.endswith("}")):
            data["msg"] = message

        data['hostname'] = self.hostname
        if global_ctx.user:
            data['user_id'] = global_ctx.user.pk
        if global_ctx.remote_addr:
            data['remote_addr'] = global_ctx.remote_addr

        # Include any other custom attributes set on the record.
        data.update({
            attr_name: record.__dict__[attr_name]
            for attr_name in record.__dict__ if attr_name not in BUILTIN_ATTRS
        })

        # If there is an error, let's format it for some nice output.
        if record.exc_info is not None:
            data["error"] = repr(record.exc_info[1])
            data["traceback"] = safer_format_traceback(*record.exc_info)

        return json.dumps(data, cls=SafeJSONEncoder)