How to add a custom loglevel to Python's logging facility

前端 未结 16 2315
旧时难觅i
旧时难觅i 2020-11-27 09:54

I\'d like to have loglevel TRACE (5) for my application, as I don\'t think that debug() is sufficient. Additionally log(5, msg) isn\'t what I want.

16条回答
  •  攒了一身酷
    2020-11-27 10:14

    This worked for me:

    import logging
    logging.basicConfig(
        format='  %(levelname)-8.8s %(funcName)s: %(message)s',
    )
    logging.NOTE = 32  # positive yet important
    logging.addLevelName(logging.NOTE, 'NOTE')      # new level
    logging.addLevelName(logging.CRITICAL, 'FATAL') # rename existing
    
    log = logging.getLogger(__name__)
    log.note = lambda msg, *args: log._log(logging.NOTE, msg, args)
    log.note('school\'s out for summer! %s', 'dude')
    log.fatal('file not found.')
    

    The lambda/funcName issue is fixed with logger._log as @marqueed pointed out. I think using lambda looks a bit cleaner, but the drawback is that it can't take keyword arguments. I've never used that myself, so no biggie.

      NOTE     setup: school's out for summer! dude
      FATAL    setup: file not found.
    

提交回复
热议问题