简体   繁体   中英

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?

Observe the role of filters in the logging flow picture . You could add a filter to a handler, that will pass through only a selected level. Here is a little demo:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
logger.addHandler(handler)

print("without filter (all levels)")
logger.debug('DEBUG1')
logger.info('INFO1')
logger.warning('WARNING1')
logger.error('ERROR1')

def logfilter(record):
    # Returns zero for no, nonzero for yes
    return record.levelno == logging.WARNING

handler.addFilter(logfilter)

print("\nwith filter (WARNING level only)")
logger.debug('DEBUG2')
logger.info('INFO2')
logger.warning('WARNING2')
logger.error('ERROR2')

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

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