日志记录模块

日志级别

  • CRITICAL 50
  • ERROR 40
  • WARNING 30
  • INFO 20
  • DEBUG 10

logging.basicConfig()函数中的具体参数含义

  • filename:指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中;
  • filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“w”还可指定为“a”;
  • format:指定handler使用的日志显示格式;
  • datefmt:指定日期时间格式。,格式参考strftime时间格式化(下文)
  • level:设置rootlogger的日志级别
  • stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数用到的格式化信息

参数描述
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s 用户输出的消息

自定义日志记录器,输出到控制台

import logging

# 创建一个日志收集器,指定具体名称的记录器
# my_logger = logging.getLogger("mylog")
my_logger = logging.getLogger('my_logger')

# 设置日志收集器等级
my_logger.setLevel("DEBUG")  # 等级参数必须大写

logger = logging.getLogger()  #默认的是root 记录器
logger.setLevel('DEBUG')     #设置root 记录器记录级别

# 设置日志输出格式
formater = logging.Formatter('%(asctime)s [%(filename)s-->line:%(lineno)d] - [%(levelname)s]: %(message)s')

# 定义输出到控制台
output_console = logging.StreamHandler()
# 设置输出到控制台日志格式
output_console.setFormatter(formater)
# 设置输出到控制台日志等级
output_console.setLevel("INFO")  # 等级参数必须大写

# 把输出到控制台,添加到日志收集器中
my_logger.addHandler(output_console)

# 需要输出的日志等级
my_logger.debug('输出日志信息为debug')
my_logger.info('输出日志信息为info')
my_logger.warning('输出日志信息为warning')
my_logger.error('输出日志信息为error')
my_logger.critical('输出日志信息为critical')

不使用baseconfig 输出到具体的文件中

import logging
# 创建一个日志收集器,指定具体名称的记录器
my_log_collector = logging.getLogger("mylog")

# 设置日志收集器等级
my_log_collector.setLevel("DEBUG")  # 等级参数必须大写

# 设置日志输出格式
formater = logging.Formatter('%(asctime)s [%(filename)s-->line:%(lineno)d] \
- %(levelname)s: %(message)s')

# 定义输出到具体路径下的文件夹,使用R/r进行格式化,输出格式为【utf-8】
output_file = logging.FileHandler(filename=r"E:\testfile\test.log", encoding='utf-8')

# 把日志格式添加到输出文件对象下
output_file.setFormatter(formater)

# 设置输出到文件夹下的日志等级
output_file.setLevel("INFO")  # 等级参数必须大写

# 把输出到控制台,添加到日志收集器中
my_log_collector.addHandler(output_file)

# 需要输出的日志等级
my_log_collector.debug('输出日志信息为debug')
my_log_collector.info('输出日志信息为info')
my_log_collector.warning('输出日志信息为warning')
my_log_collector.error('输出日志信息为error')
my_log_collector.critical('输出日志信息为critical')

使用 basicConfig 设置日志输出到文件中

import os
import logging

logging.basicConfig(
	filename=os.path.join(os.getcwd(),'all.log'),
	level=logging.DEBUG,
	format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
	filemode='a',
	datefmt='%Y-%m-%d %A %H:%M:%S',
)

logging.debug('this is a message')
原文地址:https://www.cnblogs.com/fengfengyang/p/15646805.html