Skip to content

Instantly share code, notes, and snippets.

@robdmc
Created November 4, 2015 19:23
Show Gist options
  • Select an option

  • Save robdmc/3295fb4b3d172527b97b to your computer and use it in GitHub Desktop.

Select an option

Save robdmc/3295fb4b3d172527b97b to your computer and use it in GitHub Desktop.
Python Logging Example
#! /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