How to configure all loggers in an application

前端 未结 2 1988
清酒与你
清酒与你 2021-02-19 08:08

Python\'s logging module lets modules or classes define their own loggers. And different loggers can have different handlers. Some of them may choose to log to a file, while som

2条回答
  •  野性不改
    2021-02-19 08:15

    From Logging HOWTO:

    Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)

    Any handlers you add to the root logger will be used when child loggers create log entries.

    import logging
    
    root_handler = ...
    
    root_logger = logging.getLogger()
    root_logger.addHandler(root_handler)  # Will receive all log entries
    
    # Meanwhile in a module...
    
    import logging
    
    logger = logging.getLogger(__name__)
    
    logger.error(...)  # Will go to root_handler
    

提交回复
热议问题