简单用法

  • 直接调用logging模块的方法,默认仅打印warning级别以上的日志信息,如果需要更详细的输出,可以使用logging.basicConfig()配置日志级别为DEBUG。参数范围如下:
CRITICAL
ERROR
WARNING
INFO
DEBUG
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("This is a info message")
logging.warning("This is a warning message")
logging.error("This is a error message")
logging.critical("This is a critical message")
  • 将日志输出到指定的文件,并对输出信息的格式进行定义。Formatter类中定义了格式化字符串
logformat = '%(asctime)s %(pathname)s %(funcName)s %(lineno)d %(levelname)s : %(message)s'
# filemode='a'表示追加日志
logging.basicConfig(filename='messages.log', filemode='a', level=logging.DEBUG, format=logformat)
logging.debug("This is a debug message")
logging.info("This is a info message")
logging.warning("This is a warning message")
logging.error("This is a error message")
logging.critical("This is a critical message")

高级用法

## 创建日志记录器,dlog为日志记录器的名字,可以为空,默认为root
dlog = logging.getLogger('dlog')
dlog.setLevel(logging.DEBUG)
## 日志格式器
logformat = logging.Formatter('%(asctime)s %(pathname)s %(funcName)s %(lineno)d %(levelname)s : %(message)s')
## 日志处理器
fh = logging.FileHandler(filename='messages.log', mode='a', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(logformat)

dlog.addHandler(fh)

dlog.debug("This is a debug message")
dlog.info("This is a info message")
dlog.warning("This is a warning message")
dlog.error("This is a error message")
dlog.critical("This is a critical message")

标签: none

添加新评论