Python logging multiple files using the same logger

前端 未结 3 981
难免孤独
难免孤独 2020-12-15 08:26

This is my scenario: I want to log my_module\'s activity. This needs to be done, depending on the method executed (let\'s say, INPUT and OUTPUT), to two different files.

3条回答
  •  有刺的猬
    2020-12-15 08:51

    Finally I decided to define two loggers, because:

    • They are for different purposses. In my case, one logs input request to a web service, and the other one logs the response. And they use different files to it

    • I'm using a logging config file, in a frontal web service. Adding/removing handlers before logging messages is not the right approach, as @mike said. Thx to @drekyn too!

    Here is my logging config file, just for reference if anyone is interested in:

    [loggers]
    keys=root, ws_in_log, ws_out_log
    
    [handlers]
    keys=consoleHandler, ws_in_hand, ws_out_hand
    
    [formatters]
    keys=generic_form
    
    [logger_root]
    handlers=consoleHandler
    level=NOTSET
    
    [logger_ws_in_log]
    level=NOTSET
    handlers=ws_in_hand
    qualname=ws_in_log
    
    [logger_ws_out_log]
    level=NOTSET
    handlers=ws_out_hand
    qualname=ws_out_log
    
    [handler_ws_in_hand]
    class=logging.handlers.TimedRotatingFileHandler
    level=NOTSET
    formatter=generic_form
    args=('/path/ws_in_.log', 'h', 1, 0, None, False, True)
    
    [handler_ws_out_hand]
    class=logging.handlers.TimedRotatingFileHandler
    level=NOTSET
    formatter=generic_form
    args=('/path/em/ws_out_.log', 'h', 1, 0, None, False, True)
    
    [handler_consoleHandler]
    class=StreamHandler
    level=DEBUG
    formatter=generic_form
    args=(sys.stdout,)
    
    [formatter_generic_form]
    format='%(asctime)s - %(levelname)s - %(message)s'
    datefmt='%Y-%m-%d %H:%M:%S'
    class=
    

    See you!

提交回复
热议问题