日志的固定写法

import logging
# logging.basicConfig(level=logging.DEBUG)
# logging.debug('debug message') # 最细节的 计算机计算的那些小过程
# logging.info('info message') # 普通信息 记录每个用户的操作
# logging.warning('warning message')# 警告信息 你觉得可能会影响到你程序的安全正确率的内容
# logging.error('error message') # 错误信息 直接影响你程序的健康了
# logging.critical('critical message') # 批判的 把整个userinfo文件删掉了
# 默认显示warning以上的日志

# 使用logging模块 两种方式
# 基础配置方式 : 只能完成一些简单的需求
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%a, %d %b %Y %H:%M:%S',
# filename = 'test.log',
# filemode = 'a'
# )
# logging.debug('debug message') # 最细节的 计算机计算的那些小过程
# logging.info('info message') # 普通信息 记录每个用户的操作
# logging.warning('warning message')# 警告信息 你觉得可能会影响到你程序的安全正确率的内容
# logging.error('error message') # 错误信息 直接影响你程序的健康了
# logging.critical('critical message') # 批判的 把整个userinfo文件删掉了

# 1.操作系统的编码可能会出现乱码问题
# 2.不支持同时向文件和屏幕输出
import logging
# logger对象的方式 : 灵活性 可扩展性
logger = logging.getLogger() # 创建一个logger对象
logger.setLevel(logging.DEBUG)
# 创建一个文件操作符 来准备操作日志向文件中写这件事
fh = logging.FileHandler('mylog.log',encoding='utf-8')
fh2 = logging.FileHandler('mylog2.log',encoding='utf-8')
# 创建一个屏幕操作符 来准备操作日志向屏幕中写这件事
sh = logging.StreamHandler()
# 创建一个输出格式
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 组合
# 输出格式和文件操作符屏幕操作符绑在一起
fh.setFormatter(formatter)
sh.setFormatter(formatter2)
sh.setLevel(logging.ERROR)
# logger对象分别和文件操作符屏幕操作符绑在一起
logger.addHandler(fh)
logger.addHandler(fh2)
logger.addHandler(sh)

# 才开始能够使用logger来记录日志
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
原文地址:https://www.cnblogs.com/awfj/p/10066385.html