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'.
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'.
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
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.')
logging
provides a RotatingFileHandler
that lets you rotate log files easily. –
Lament © 2022 - 2024 — McMap. All rights reserved.