背景:自己写的日志打印模块,用pytest -n=auto 后日志就不会输出
# tools.set_loggging.py
import logging.handlers
import sys
from concurrent_log_handler import ConcurrentRotatingFileHandler
from config import BASE_PATH
def set_log(log_name):
# 1. 创建日志器对象
logger = logging.getLogger()
# 2. 设置日志打印级别
logger.setLevel(logging.INFO)
# 3. 创建处理器对象
# 输出到控制台
st = logging.StreamHandler()
# 输出到日志文件
# when 是一个字符串,定义了日志切分的间隔时间单位
# interval 是间隔时间单位的个数,指等待多少个 when 的时间后继续进行日志记录
# backupCount 是保留日志的文件个数
fh = logging.handlers.TimedRotatingFileHandler(BASE_PATH + '/logs/' + log_name,
when='midnight',
interval=1,
backupCount=3,
encoding='utf-8')
# 4. 创建格式化器
fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
formatter = logging.Formatter(fmt)
# 5. 给处理器设置格式化器
st.setFormatter(formatter)
fh.setFormatter(formatter)
# 6. 给日志器添加处理器
logger.addHandler(st)
logger.addHandler(fh)
def set_current_log(log_name):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s")
if not logger.handlers: # 判断是否有handlers,有直接记录日志, 不需要创建多个句柄,否则会有日志重复打印问题
# ConcurrentRotatingFileHandler
rotateHandler = ConcurrentRotatingFileHandler(BASE_PATH + '/logs/' + log_name, maxBytes=512 * 1024, backupCount=10,
encoding='utf-8')
rotateHandler.setLevel(logging.INFO)
rotateHandler.setFormatter(formatter)
logger.addHandler(rotateHandler)
# stream_handler = logging.StreamHandler()
# stream_handler.setLevel(logging.INFO)
# stream_handler.setFormatter(formatter)
# logger.addHandler(stream_handler)
解决办法:
标签:插件,logging,log,handler,pytest,日志,formatter,logger From: https://www.cnblogs.com/czzz/p/16939712.html脚本路径下或者项目跟路径下添加conftest.py 再初始化日志