Skip to content

Instantly share code, notes, and snippets.

@Dulani
Created November 18, 2017 03:19
Show Gist options
  • Save Dulani/440c220a9fb0007d8c2ecf67e3d29492 to your computer and use it in GitHub Desktop.
Save Dulani/440c220a9fb0007d8c2ecf67e3d29492 to your computer and use it in GitHub Desktop.
Example logging code for Python (since I'm always having to look it up).
#!/usr/bin/env python
"""
Originally taken from my pandoc filter code.
It has good examples of logging in use.
"""
import logging
LOG_FILENAME = 'my_log_name_here.log'
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Set up a specific logger with our desired output level
named_logger = logging.getLogger('Name this logger')
named_logger.setLevel(logging.DEBUG)
# Create file handler which logs even debug messages
fh = logging.FileHandler(LOG_FILENAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
# add the handler to logger
named_logger.addHandler(fh)
# Create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
# add the handler to the logger
named_logger.addHandler(ch)
named_logger.warning('This is a warning entry.')
named_logger.debug('This is a debug entry.')
named_logger.info('This is an information entry.')
def function_with_logging(someText):
named_logger.info("Text in argument: %s", someText)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment