Deepanshu Arora
Deepanshu Arora

Reputation: 435

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?

Upvotes: 1

Views: 1491

Answers (1)

Lior Cohen
Lior Cohen

Reputation: 5755

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.

Upvotes: 1

Related Questions