Skip to content

Instantly share code, notes, and snippets.

@wolfiex
Last active November 26, 2020 00:57
Show Gist options
  • Save wolfiex/f693b7aeaa70bf94a009bcc510a9690d to your computer and use it in GitHub Desktop.
Save wolfiex/f693b7aeaa70bf94a009bcc510a9690d to your computer and use it in GitHub Desktop.
Loggingdemo
import logging
'''
Set up logger
'''
log = logging.getLogger(__file__.rsplit('/',1)[1]) ## if running interactively with ipython, replace this with a descriptive string
log.propagate = False
log.setLevel(logging.DEBUG)
logfile = 'test.log'
'''
remove existing handlers
'''
while log.hasHandlers():
log.removeHandler(log.handlers[0])
'''
Console Stream
'''
console = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)-10s %(message)s')
console.setFormatter(formatter)
console.setLevel(logging.INFO)
log.addHandler(console)
'''
File Debug
'''
tofile = logging.FileHandler(logfile, mode='a')
formatter = logging.Formatter('%(asctime)s ~ %(name)s ~ %(levelname)s ~ %(message)s')
tofile.setFormatter(formatter)
tofile.setLevel(logging.DEBUG)
log.addHandler(tofile)
'''
testData
'''
log.warning('Arrgghh!')
log.info('This is an info message!')
log.debug('Lets hope the user does not see this bug')
'''
Optional: replace print function with logger
'''
def print(*argv):
return log.info(' '.join(map(str,argv)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment