Skip to content

Instantly share code, notes, and snippets.

@jakebrinkmann
Forked from kdgregory/logging_example.py
Created June 5, 2024 16:37
Show Gist options
  • Select an option

  • Save jakebrinkmann/02253a69f16ef2bcafce4b07de9fa70b to your computer and use it in GitHub Desktop.

Select an option

Save jakebrinkmann/02253a69f16ef2bcafce4b07de9fa70b to your computer and use it in GitHub Desktop.

Revisions

  1. @kdgregory kdgregory revised this gist Jul 27, 2018. 1 changed file with 15 additions and 1 deletion.
    16 changes: 15 additions & 1 deletion logging_example.py
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,15 @@
    import traceback

    class JSONFormatter:
    """A formatter for the standard logging module that converts a LogRecord into JSON
    Output matches JSONLayout from https://github.com/kdgregory/log4j-aws-appenders. Any
    keyword arguments supplied to the constructor are output in a "tags" sub-object.
    """

    def __init__(self, **tags):
    self.tags = tags

    def format(self, record):
    result = {
    'timestamp': time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) +
    @@ -21,13 +30,18 @@ def format(self, record):
    'lineNumber': record.lineno
    }
    }

    if self.tags:
    result['tags'] = self.tags

    if (record.exc_info):
    result['exception'] = traceback.format_exception(record.exc_info[0], record.exc_info[1], record.exc_info[2])

    return json.dumps(result)

    def configure_logging():
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(JSONFormatter())
    handler.setFormatter(JSONFormatter(application="example"))
    logging.basicConfig(level=logging.DEBUG, handlers=[handler])


  2. @kdgregory kdgregory created this gist Jul 25, 2018.
    43 changes: 43 additions & 0 deletions logging_example.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    import json
    import logging
    import platform
    import sys
    import time
    import traceback

    class JSONFormatter:
    def format(self, record):
    result = {
    'timestamp': time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) +
    (".%03dZ" % (1000 * (record.created % 1))),
    'level': record.levelname,
    'logger': record.name,
    'message': record.msg % record.args,
    'hostname': platform.node(),
    'processId': record.process,
    'thread': record.threadName,
    'locationInfo': {
    'fileName': record.filename,
    'lineNumber': record.lineno
    }
    }
    if (record.exc_info):
    result['exception'] = traceback.format_exception(record.exc_info[0], record.exc_info[1], record.exc_info[2])
    return json.dumps(result)

    def configure_logging():
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(JSONFormatter())
    logging.basicConfig(level=logging.DEBUG, handlers=[handler])


    if __name__ == '__main__':
    configure_logging()
    logger = logging.getLogger(__name__)
    logger.info('Started')
    logger.debug('this is a test of %s %s', "value", "substitutions")
    try:
    raise Exception("example")
    except Exception as ex:
    logger.exception("caught exception")
    logger.info('Finished')