Skip to content

Instantly share code, notes, and snippets.

@adejones
Created October 20, 2016 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adejones/8899fc85e8ebc453950a6e92cc965fd4 to your computer and use it in GitHub Desktop.
Save adejones/8899fc85e8ebc453950a6e92cc965fd4 to your computer and use it in GitHub Desktop.
import logging
import logging.handlers
# log file name and logging message level
log_file_name = 'loggingexample.log'
log_level = logging.INFO
# log record format string
format_string = '%(asctime)s %(name)s %(levelname)s %(message)s'
# set default logging (to console)
logging.basicConfig(level=log_level, format=format_string)
# set logging to file
log_formatter = logging.Formatter(format_string)
file_handler = logging.FileHandler(log_file_name, mode='w') # mode is file write mode, 'a' to append
file_handler.setFormatter(log_formatter)
# create child logger and set it to be a file handler
logger = logging.getLogger() # or pass a string to give it a name
logger.addHandler(file_handler)
logger.setLevel(log_level)
# log some messages
logger.info("Started")
logger.info("This is an example entry")
logger.debug("This line won't get logged as the log level is INFO")
logger.info("Done.")
# perform an orderly shutdown by flushing and closing all handlers; called at application exit and no further use of the logging system should be made after this call.
logging.shutdown()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment