Skip to content

Instantly share code, notes, and snippets.

@ryantuck
Last active March 14, 2017 19:12
Show Gist options
  • Save ryantuck/fae22b9e7b5223bbfff408a2874f9e51 to your computer and use it in GitHub Desktop.
Save ryantuck/fae22b9e7b5223bbfff408a2874f9e51 to your computer and use it in GitHub Desktop.
logging demo in python
import logging
log = logging.getLogger('my-app.aux')
def log_this(msg):
if isinstance(msg, int):
log.debug('{} is an int!'.format(msg))
return None
if msg is None:
log.error('{} is None!'.format(msg))
return None
log.info(msg)
# python logging demo
# logging hierarchy:
# CRITICAL
# ERROR
# WARNING
# INFO
# DEBUG
# NOTSET (*)
import logging
# some random module that also logs stuff
import aux
# create a logger!
log = logging.getLogger('my-app')
# define our minimum default logging level (basically everything)
log.setLevel(logging.DEBUG)
# handler for writing to a file
# (level set to info to reduce unnecessary chatter)
fh = logging.FileHandler('stuff.log')
fh.setLevel(logging.INFO)
# handler for streaming to stdout
# (level set to debug to see everything)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# define logging format - here i'm doing some fixed-width formatting stuff
file_formatter = logging.Formatter(
fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)
stdout_formatter = logging.Formatter(
fmt='%(levelname)-10s | %(message)s',
)
# set the formatting for both outputs
fh.setFormatter(file_formatter)
ch.setFormatter(stdout_formatter)
# add both handlers to our log object
log.addHandler(fh)
log.addHandler(ch)
def main():
log.info('running main')
aux.log_this(5)
aux.log_this('hello')
# do something that will break
x = a/5
if __name__ == '__main__':
try:
main()
except:
# this will also log the traceback
log.exception('tried running main')
raise
2017-03-14 15:10:00,562 | my-app | INFO | running main
2017-03-14 15:10:00,562 | my-app.aux | INFO | hello
2017-03-14 15:10:00,562 | my-app | ERROR | tried running main
Traceback (most recent call last):
File "main.py", line 63, in <module>
main()
File "main.py", line 57, in main
x = a/5
NameError: global name 'a' is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment