I am fairly new in python and starting to get into the logging module. I would like to have the message logged into a log file and outputting to the console. The code below prints out the message to console but how can I get all the message to be log in a file?
Logger object does not have a function call (basicConfig(filename=)) for logging to a file. How can I add this functionality?
Thanks for the help in advance.
import logging # create logger logger = logging.getLogger(_name_) logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')
Advertisement
Answer
You just need to add another handler, like a logging.FileHandler
fh = logging.FileHandler(r'/path/to/log.txt') logger.addHandler(fh)