简体   繁体   中英

How to redirect logging on root logger to custom logger?

I have a use case where I want all logs to go to a single file. I am using a custom logger on which I define the file handler to log to desired file.

The problem I'm facing is the external modules which I use are using root loggers and I wan't them also to log to same file.

Custom logger module


def initialize_logger():
    logger = logging.getLogger("custom")
    file_handler = FileHandler(filename="test")
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(FORMATTER)
    logger.addHandler(file_handler)
    return logger

def get_logger():
    return logging.getLogger("custom")


Modules in my application are using the following code


from log import get_logger
logger = get_logger()

logger.info("Test")

External modules which I am using are having the following line.

logging.info("test")

Is there a way I can capture logs in external modules in same file?

Just add your handler to the root logger, instead of your logger.

root_logger = logging.getLogger()
root_logger.addHandler(...)

This way, any log will reach to this file-handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM