pythonpython-3.xloggingloguru

How to write each level to a separate file so that it does not repeat in each file below the level?


logger.configure(
    handlers=[
        dict(sink="TRACE.log", level='TRACE', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="DEBUG.log", level='DEBUG', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="INFO.log", level='INFO', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="SUCCESS.log", level='SUCCESS', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="WARNING.log", level='WARNING', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="ERROR.log", level='ERROR', enqueue=True, encoding='utf-8', diagnose=True),
        dict(sink="CRITICAL.log", level='CRITICAL', enqueue=True, encoding='utf-8', diagnose=True),

    ],
)

logger.trace('TRACE')
logger.debug('DEBUG')
logger.info('INFO')
logger.success('SUCCESS')
logger.warning('WARNING')
logger.error('ERROR')
logger.critical('CRITICAL')](url)

TRACE.log

2021-12-26 15:44:39.272 | TRACE    | __main__:main:216 - TRACE
2021-12-26 15:44:39.272 | DEBUG    | __main__:main:217 - DEBUG
2021-12-26 15:44:39.272 | INFO     | __main__:main:218 - INFO
2021-12-26 15:44:39.272 | SUCCESS  | __main__:main:219 - SUCCESS
2021-12-26 15:44:39.272 | WARNING  | __main__:main:220 - WARNING
2021-12-26 15:44:39.288 | ERROR    | __main__:main:221 - ERROR
2021-12-26 15:44:39.288 | CRITICAL | __main__:main:222 - CRITICAL

How to write each level to a separate file so that it does not repeat in each file below the level?


Solution

  • Use the filter parameter:

    import sys
    
    from loguru import logger
    
    
    def only_level(level):
        def is_level(record):
            return record['level'].name == level
    
        return is_level
    
    
    logger.remove()
    logger.add(sys.stdout, level='TRACE', filter=only_level('TRACE'))
    
    logger.trace('TRACE')
    logger.debug('DEBUG')  # will not be logged