loggingloguru

Multiple handlers/levels logging in Loguru (Python module)


I am making use of loguru in a Python app.

I have now come to the stage where I would like different handlers to write to stderr and file with different levels respectively.

So for stderr I want it to only log "DEBUG" level logs (i.e. logger.debug("my debug log")).

For write to file I want it to only log "INFO" level logs (i.e. logger.info("my info log")).

So in my main app.py I have added the loggers as per the docs like so:

import sys

from loguru import logger

from my_module import my_function

logger.add(sys.stderr, level="DEBUG")
logger.add("logs/file1.log", level="INFO")

results = my_function()

Then I have my_function() defined in my_module.py like so:

from loguru import logger


def my_function():

   logger.info("Start fn")
   # some sql query
   logger.debug("Debug message")
   logger.info("Finishes fn")

But this current setup just logs both debug and info levels to both handlers. I read here on their github, that importing from loguru in submodules is enough for the future calls to propagated to the configured handlers.

However in my case not, is there something I am missing?


Solution

  • If you want to log a specific level of log messages, exclude the higher levels, you could add a filter:

    import logging
    import sys
    from loguru import logger
    
    logger.remove() # Remove Loguru default handler
    
    logger.add(
      sink=sys.stderr,
      level=logging.DEBUG,
      filter=lambda record: record['level'].name == 'DEBUG'
    )
    

    In this case, stderr only prints debug logs.