Python开发【内置模块篇】日志模块

logging配置

 1 import logging
 2 logging.basicConfig(level=logging.WARNING,
 3                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
 4                     datefmt='%a, %d %b %Y %H:%M:%S')
 5 try:
 6     int(input('num >>'))
 7 except ValueError:
 8     logging.error('输入的值不是一个数字')
 9 
10 logging.debug('debug message')       # 低级别的 # 排错信息
11 logging.info('info message')            # 正常信息
12 logging.warning('warning message')      # 警告信息
13 logging.error('error message')          # 错误信息
14 logging.critical('critical message') # 高级别的 # 严重错误信息
basicConfig
num >>hh
Sun, 30 Dec 2018 16:13:03 1.py[line:8] ERROR 输入的值不是一个数字
Sun, 30 Dec 2018 16:13:03 1.py[line:12] WARNING warning message
Sun, 30 Dec 2018 16:13:03 1.py[line:13] ERROR error message
Sun, 30 Dec 2018 16:13:03 1.py[line:14] CRITICAL critical message
输出结果

配置log对象

import loggin

logger = logging.getLogger()

fh = logging.FileHandler('log.log',encoding='utf-8')
sh = logging.StreamHandler()    # 创建一个屏幕控制对象

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] : %(message)s')

# 文件操作符 和 格式关联
fh.setFormatter(formatter)
sh.setFormatter(formatter2)


# logger 对象 和 文件操作符 关联
logger.addHandler(fh)
logger.addHandler(sh)
logging.debug('debug message')       # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('警告错误')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message') # 高级别的 # 严重错误信息
View Code
2018-12-30 16:14:03,252 - root - WARNING [line:21] : 警告错误
2018-12-30 16:14:03,253 - root - ERROR [line:22] : error message
2018-12-30 16:14:03,253 - root - CRITICAL [line:23] : critical message
屏幕输出
1 2018-12-30 16:14:03,252 - root - WARNING - 警告错误
2 2018-12-30 16:14:03,253 - root - ERROR - error message
3 2018-12-30 16:14:03,253 - root - CRITICAL - critical message
log.log文件
原文地址:https://www.cnblogs.com/tangkaishou/p/10199758.html