How to write to a file, using the logging Python module?
Taken from the "logging cookbook":
# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
And you're good to go.
P.S. Make sure to read the logging HOWTO as well.
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
- set the output file (
filename=logname
) - set it to append rather than overwrite (
filemode='a'
) - determine the format of the output message (
format=...
) - determine the format of the output time (
datefmt='%H:%M:%S'
) - and determine the minimum message level it will accept (
level=logging.DEBUG
).