Click name ↑ to return to homepage
#!/usr/bin/env python
import logging
log_filename = "log.txt"
# make a logging object
log = logging.getLogger('logger') #inherits from parent - root
# will print info and debug to log file
log.setLevel(logging.DEBUG)
# set up the two formats for the two handlers
# more detailed message for the log file
file_formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s - %(message)s',
datefmt="%Y-%m-%d %H:%M:%S")
# simpler message for the screen
stream_formatter = logging.Formatter(fmt='%(message)s')
# make a file handler object
fh = logging.FileHandler(log_filename, mode='w', encoding='utf-8')
fh.setLevel(logging.DEBUG) #info and debug print to file
# add in the formatting, specified above
fh.setFormatter(file_formatter)
# then add it to the logging object called log
log.addHandler(fh)
# make a stream handler object
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) #just info prints to screen
ch.setFormatter(stream_formatter)
log.addHandler(ch)
# check that info goes to screen AND log file
log.info("logging info here")
# check the debug goes to log file only
log.debug("logging debug here")