How can I use the logging module in Python to write to a file? Every time I try to use it, it just prints out the message.
here's a simpler way to go about it. this solution doesn't use a config dictionary and uses a rotation file handler, like so:
import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
format='%(levelname)s %(asctime)s %(message)s',
datefmt='%m/%d/%Y%I:%M:%S %p')
logger = logging.getLogger('my_logger')
or like so:
import logging
from logging.handlers import RotatingFileHandler
handlers = [
RotatingFileHandler(filename=logpath+filename, mode='w', maxBytes=512000,
backupCount=4)
]
logging.basicConfig(handlers=handlers, level=debug_level,
format='%(levelname)s %(asctime)s %(message)s',
datefmt='%m/%d/%Y%I:%M:%S %p')
logger = logging.getLogger('my_logger')
the handlers variable needs to be an iterable. logpath+filename and debug_level are just variables holding the respective info. of course, the values for the function params are up to you.
the first time i was using the logging module i made the mistake of writing the following, which generates an OS file lock error (the above is the solution to that):
import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(filename=logpath+filename, level=debug_level, format='%(levelname)s %(asctime)s %(message)s', datefmt='%m/%d/%Y
%I:%M:%S %p')
logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(filename=logpath+filename, mode='w',
maxBytes=512000, backupCount=4))
and Bob's your uncle!