Python logging - two loggers, two log files - how to configure logging.ini
Asked Answered
A

1

5

It can be practical to have two or more distinct log files. For example for a Rest service, have one log file for general failures and another for faults in the content.

I tried doing this using INI-file but for some reason all the logs would go to both files. So...

How would the logging.ini look like if I want all logs from logger1 to go to logger1.log and all logs from logger2 to go to logger2.log:

logging.config.fileConfig('logging.ini')
logger1 = logging.getLogger('name1')
logger2 = logging.getLogger('name2')
Allodial answered 30/8, 2019 at 17:8 Comment(0)
A
7

This works:

python_logging.py

import logging
from logging import config

logging.config.fileConfig('logging.ini')
logger1 = logging.getLogger('name1')
logger2 = logging.getLogger('name2')

logger1.debug('This is logger1')
logger2.info('This is logger2')
logger1.warning('This is logger1')
logger1.error('This is logger1')
logger2.warning('This is logger2')
logger2.error('This is logger2')

logging.ini:

[loggers]
keys=root,name1,name2

[handlers]
keys=console_handler,file_handler_name1,file_handler_name2

[formatters]
keys=console_formatter,file_formatter

[logger_root]
level=INFO
handlers=

[logger_name1]
level=INFO
handlers=console_handler,file_handler_name1
qualname=name1

[logger_name2]
level=INFO
handlers=console_handler,file_handler_name2
qualname=name2

[handler_console_handler]
class=StreamHandler
formatter=console_formatter
args=(sys.stdout,)

[handler_file_handler_name1]
class=handlers.RotatingFileHandler
formatter=file_formatter
args=('name1.log','a',1000000,100)

[handler_file_handler_name2]
class=handlers.RotatingFileHandler
formatter=file_formatter
args=('name2.log','a',1000000,100)

[formatter_console_formatter]
format=%(asctime)s %(levelname)s | %(name)s | %(message)s'
datefmt='%d-%m-%Y %H:%M:%S

[formatter_file_formatter]
format=%(asctime)s %(levelname)s | %(name)s | %(message)s'
datefmt='%d-%m-%Y %H:%M:%S
Allodial answered 1/9, 2019 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.