logging调试程序python

使用logging类记录错误

  • 我们可以使用print()来调试程序,但如果到处是print(),想关闭又得一个个去修改。
  • 使用logging类,我们可以记录各种级别的错误,通过配置参数,可以控制显示哪些错误记录。

错误级别:

  • CRITICAL = 50
  • FATAL = CRITICAL
  • ERROR = 40
  • WARNING = 30
  • WARN = WARNING
  • INFO = 20
  • DEBUG = 10
  • NOTSET = 0

    对应的方法:

  • logging.critical()
  • logging.fatal()
  • logging.error()
  • logging.warning()
  • logging.warn()
  • logging.info()

  • logging.debug()
例子1 控制logging level为error
#!/usr/bin/python
# coding: utf-8

import logging

# logging.basicConfig(level=logging.NOTSET)
logging.basicConfig(level=logging.ERROR)

def cal(m, n):
    if n == 0:
        # raise ValueError('Illegal value: %d' % n)
        logging.info('Illegal value: %d' % n)
        
    logging.debug("debug_test")
    logging.warning("warning_test")
    logging.info("info_test")
    logging.error("error_test")
    logging.fatal("fatal_test")
    return  m * n

try:
    r = cal(6, 0)
    print(r)
except Exception as e:
    print(e)
输出:
ERROR:root:error_test
CRITICAL:root:fatal_test
例子2 控制logging level为WARNING
#!/usr/bin/python
# coding: utf-8

import logging

# logging.basicConfig(level=logging.NOTSET)
logging.basicConfig(level=logging.WARNING)

def cal(m, n):
    if n == 0:
        # raise ValueError('Illegal value: %d' % n)
        logging.info('Illegal value: %d' % n)
        
    logging.debug("debug_test")
    logging.warning("warning_test")
    logging.info("info_test")
    logging.error("error_test")
    logging.fatal("fatal_test")
    return  m * n

try:
    r = cal(6, 0)
    print(r)
except Exception as e:
    print(e)
输出:
WARNING:root:warning_test
ERROR:root:error_test
CRITICAL:root:fatal_test
例子3 控制logging level为DEBUG
#!/usr/bin/python
# coding: utf-8

import logging

# logging.basicConfig(level=logging.NOTSET)
logging.basicConfig(level=logging.DEBUG)

def cal(m, n):
    if n == 0:
        # raise ValueError('Illegal value: %d' % n)
        logging.info('Illegal value: %d' % n)
        
    logging.debug("debug_test")
    logging.warning("warning_test")
    logging.info("info_test")
    logging.error("error_test")
    logging.fatal("fatal_test")
    return  m * n

try:
    r = cal(6, 0)
    print(r)
except Exception as e:
    print(e)

输出:
INFO:root:Illegal value: 0
DEBUG:root:debug_test
WARNING:root:warning_test
INFO:root:info_test
ERROR:root:error_test
CRITICAL:root:fatal_test



你可能感兴趣的:(deeplearning4j)