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.
JavaScript
x
26
26
1
import logging
2
3
# create logger
4
logger = logging.getLogger(_name_)
5
logger.setLevel(logging.DEBUG)
6
7
# create console handler and set level to debug
8
ch = logging.StreamHandler()
9
ch.setLevel(logging.DEBUG)
10
11
# create formatter
12
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
13
14
# add formatter to ch
15
ch.setFormatter(formatter)
16
17
# add ch to logger
18
logger.addHandler(ch)
19
20
# 'application' code
21
logger.debug('debug message')
22
logger.info('info message')
23
logger.warn('warn message')
24
logger.error('error message')
25
logger.critical('critical message')
26
Advertisement
Answer
You just need to add another handler, like a logging.FileHandler
JavaScript
1
3
1
fh = logging.FileHandler(r'/path/to/log.txt')
2
logger.addHandler(fh)
3