Skip to content

Instantly share code, notes, and snippets.

@louiscklaw
Created May 6, 2017 16:36
Show Gist options
  • Save louiscklaw/4569c5e9e515809e2dd47d4b6933e988 to your computer and use it in GitHub Desktop.
Save louiscklaw/4569c5e9e515809e2dd47d4b6933e988 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import logging
"""
I never remember all the steps for setting up logging in python.
This gist goes through the steps so I can copy and paste what I need.
"""
# create logger on the current module and set its level
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
# create a formatter that creates a single line of json with a comma at the end
formatter = logging.Formatter(
(
'{"unix_time":%(created)s, "time":"%(asctime)s", "module":"%(name)s",'
' "line_no":%(lineno)s, "level":"%(levelname)s", "msg":"%(message)s"},'
)
)
# create a channel for handling the logger and set its format
ch = logging.StreamHandler()
ch.setFormatter(formatter)
# connect the logger to the channel
ch.setLevel(logging.INFO)
logger.addHandler(ch)
# send an example message
logger.info('logging is working')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment