在for循环中创建logger日志,产生冗余日志
冗余日志
import logging
import os
def create_directory_file(log_path):
"""
创建目录,如果目录不存在则创建目录。
"""
# 获取目录路径
directory = os.path.dirname(log_path)
# 如果目录不存在,则创建目录
if not os.path.exists(directory):
os.makedirs(directory)
print(f"Directory created: {directory}")
else:
print(f"Directory already exists: {directory}")
def get_logger(filename, verbosity=1, name=None): # 文件进行追加而不是重写
"""
:param filename: 日志文件名
:param verbosity:
:param name:
:return:
"""
level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}
formatter = logging.Formatter(
"[%(asctime)s][%(levelname)s] %(message)s"
)
logger = logging.getLogger(name)
logger.setLevel(level_dict[verbosity])
# fh = logging.FileHandler(filename, "w") # 如果有w表示不会追加 每次会从新写入文件
fh = logging.FileHandler(filename)
fh.setFormatter(formatter)
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger, fh, sh
if __name__ == '__main__':
for i in range(2):
for j in range(2):
log_path = "./log/{}.log".format("test") # 日志文件
create_directory_file(log_path) # 创建目录
logger, fh, sh = get_logger(log_path)
logger.info("{}:{}".format(i, j))
输出:
去除冗余
- 在添加handler前进行判断;
import logging
import os
def create_directory_file(log_path):
"""
创建目录,如果目录不存在则创建目录。
"""
# 获取目录路径
directory = os.path.dirname(log_path)
# 如果目录不存在,则创建目录
if not os.path.exists(directory):
os.makedirs(directory)
print(f"Directory created: {directory}")
else:
print(f"Directory already exists: {directory}")
def get_logger(filename, verbosity=1, name=None):
"""
:param filename: 日志文件名
:param verbosity: 日志级别
:param name: 日志记录器名称
:return: logger, fh, sh
"""
level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}
formatter = logging.Formatter(
"[%(asctime)s][%(levelname)s] %(message)s"
)
# 创建一个新的 logger,名称使用文件名(或传入的名称)
logger = logging.getLogger(name if name else filename)
logger.setLevel(level_dict[verbosity])
# 检查是否已经有处理器,避免冗余添加
if not logger.handlers:
fh = logging.FileHandler(filename)
fh.setFormatter(formatter)
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger, fh, sh
if __name__ == '__main__':
for i in range(2):
for j in range(3):
log_path = "./log/{}_{}.log".format(i, j) # 为每个组合生成不同的日志文件
create_directory_file(log_path) # 创建目录
logger, fh, sh = get_logger(log_path) # 为每个文件创建唯一的 logger
logger.info("{}:{}".format(i, j))
参考博客: https://blog.csdn.net/Moonlight_16/article/details/123334339