Python logging - Is there something below DEBUG?

前端 未结 4 1827
闹比i
闹比i 2021-02-01 06:53

In some other technologies we occasionally used a log level below DEBUG that I believe was called \"verbose\". I realize that the need for such a level is very subjective. But

相关标签:
4条回答
  • 2021-02-01 07:10

    You can even go further and add a logger.verbose method, although I strongly suggest you don't for various reasons (pretty much covered in logging's how-to). Anyway, if you decide that you really want to have one, here's the code:

    logging.VERBOSE = 5
    logging.addLevelName(logging.VERBOSE, "VERBOSE")
    logging.Logger.verbose = lambda inst, msg, *args, **kwargs: inst.log(logging.VERBOSE, msg, *args, **kwargs)
    
    0 讨论(0)
  • 2021-02-01 07:18

    DEBUG is the lowest level out of the ones provided by the logging module: ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'). Their numeric values are here: http://docs.python.org/howto/logging.html#logging-levels

    You can create custom levels (though the docs say that that should rarely be necessary and may even be undesirable). If you want to add a level, the technique is simple:

    >>> logging.addLevelName(5, "VERBOSE")
    

    Eventhough you can add a custom level, it may be a better approach to add some filters that provide a finer level of control.

    0 讨论(0)
  • 2021-02-01 07:21

    The answer from @voitek works great, but he forgot to monkey patch logging.verbose.

    logging.VERBOSE = 5
    logging.addLevelName(logging.VERBOSE, "VERBOSE")
    logging.Logger.verbose = lambda inst, msg, *args, **kwargs: inst.log(logging.VERBOSE, msg, *args, **kwargs)
    logging.verbose = lambda msg, *args, **kwargs: logging.log(logging.VERBOSE, msg, *args, **kwargs)
    

    This will now also work with;

    logging.verbose(*args, **kwargs)
    
    0 讨论(0)
  • 2021-02-01 07:23

    Adding to @sleepycal's answer, you might also want to add a verbose method to the LoggerAdapter:

    logging.VERBOSE = 5
    logging.addLevelName(logging.VERBOSE, "VERBOSE")
    logging.Logger.verbose = lambda inst, msg, *args, **kwargs: inst.log(logging.VERBOSE, msg, *args, **kwargs)
    logging.LoggerAdapter.verbose = lambda inst, msg, *args, **kwargs: inst.log(logging.VERBOSE, msg, *args, **kwargs)
    logging.verbose = lambda msg, *args, **kwargs: logging.log(logging.VERBOSE, msg, *args, **kwargs)
    
    0 讨论(0)
提交回复
热议问题