Python中logging.info使用异常求助:出现Message与Arguments输出
Python日志输出疑问排查
问题场景
编写了用于文件夹间图像重排的Python代码,执行logging.info语句时,出现了包含原调用语句、格式化后消息及空参数的输出,疑惑操作是否有误。
代码片段
import logging import glob # 假设args已通过命令行或其他方式定义 logging.basicConfig(filename = 'make_folders.log', filemode= 'w', level=logging.INFO, format='%(asctime)::%(message)s') def get_path_list(directory: str) -> list: """ Get a list of absolute paths of all the files in the directory. :param directory: Path to the directory from which the file paths are to be extracted. """ path_list =[] for file in glob.glob(pathname=directory+'/*.png', recursive=True): path_list.append(file) return path_list # 收集文件夹A和B中的所有图像路径 img_A = get_path_list(args.source_A) img_B = get_path_list(args.source_B) try: assert len(img_A) == len(img_B) except AssertionError: logging.error("The number of images in source_A folder and source_B folder are not the same. Check input folders.") # 划分训练、验证、测试集的数量 train_len = round(0.7 * len(img_A)) val_len = round(0.15 * len(img_A)) test_len = val_len logging.info("Total number of training, validation and test images in destination folder A and B are {}, {} and {} respectively".format(train_len, val_len, test_len))
异常输出
logging.info("Total number of training, validation and test images in destination folder A and B are {}, {} and {} respectively".format(train_len, val_len, test_len)) Message: 'Total number of training, validation and test images in destination folder A and B are 5265, 1128 and 1128 respectively' Arguments: ()
问题分析与解决
核心结论:你没有功能错误,日志消息已经正确生成。你看到的这段输出并非日志文件
make_folders.log里的内容,而是你使用的IDE或调试工具的调试信息,它展示了logging.info的调用语句、最终生成的消息以及传递给日志函数的额外参数(这里为空)。规范写法优化:虽然当前代码能正常工作,但更推荐利用
logging模块内置的格式化能力,无需提前用str.format拼接字符串:
logging.info("Total number of training, validation and test images in destination folder A and B are {}, {} and {} respectively", train_len, val_len, test_len)
这种写法的优势:
- 日志系统会自动处理格式化,性能更优
- 日志框架能保留原始消息模板和参数,便于后续的日志分析或二次处理
- 验证日志文件:打开
make_folders.log文件,里面应该已经按照你设置的格式输出了正确内容,示例格式:
2024-05-20 14:30:00,123::Total number of training, validation and test images in destination folder A and B are 5265, 1128 and 1128 respectively
- 额外代码优化建议:
- 路径拼接不要直接用
+,改用os.path.join(directory, '*.png'),避免因目录末尾有无斜杠导致的路径错误 glob.glob的recursive=True在匹配*.png时无意义(该模式不会匹配子目录),可移除该参数
- 路径拼接不要直接用
内容的提问来源于stack exchange,提问作者programmer_04_03
相关产品推荐
相关产品推荐

