Created
November 4, 2015 19:23
-
-
Save robdmc/3295fb4b3d172527b97b to your computer and use it in GitHub Desktop.
Python Logging Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /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