python logging to multiple files
Asked Answered
W

2

15

Does someone has an example of logging in python to 2 or more different logfiles.

I want to log for example to '/tmp/foo.log' and '/tmp/bar.log'.

Woman answered 7/4, 2011 at 7:45 Comment(0)
S
19

Here's an example:

import logging
logger1 = logging.getLogger('1')
logger1.addHandler(logging.FileHandler('/tmp/logger1'))
logger2 = logging.getLogger('2')
logger2.addHandler(logging.FileHandler('/tmp/logger2'))

logger1.error('1')
logger2.error('2')

Then,

 $ cat /tmp/logger1
 1
 $ cat /tmp/logger2
 2
Stomach answered 7/4, 2011 at 8:2 Comment(0)
L
4

Here's a complete working example based on the example in logging.html. The main 'gotcha' to note is that you have to be sure to set the log level for the root logger to interact correctly with the files.

import logging

logging.getLogger('').setLevel(logging.DEBUG)
def create_log_file(filename, level=logging.INFO):
    handler = logging.FileHandler(filename)
    handler.setLevel(level)
    formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    handler.setFormatter(formatter)
    logging.getLogger('').addHandler(handler)

create_log_file('/temp/log1.log', logging.DEBUG)
create_log_file('/temp/log2.log', logging.INFO)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
Leannaleanne answered 7/4, 2011 at 8:16 Comment(4)
but in this example all root messages will apear in log1.log and log2.log aswell?Woman
that's because it is just an example. If you want you can attach the handlers to a different logger.Leannaleanne
Why you attack this post, i just asked for an example and the post of Duncan helped me much better than the documentation. So thank you Duncan for your help. But 1 more question, is it possible to put on each logger a rotation ?Woman
@Hein: try the Python 3.2 version of the docs, they may make more sense than the 2.7 version: docs.python.org/py3k/library/logging.html. And yes, logging provides a RotatingFileHandler that lets you rotate log files easily.Lament

© 2022 - 2024 — McMap. All rights reserved.