You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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: ()

问题分析与解决

  1. 核心结论:你没有功能错误,日志消息已经正确生成。你看到的这段输出并非日志文件make_folders.log里的内容,而是你使用的IDE或调试工具的调试信息,它展示了logging.info的调用语句、最终生成的消息以及传递给日志函数的额外参数(这里为空)。

  2. 规范写法优化:虽然当前代码能正常工作,但更推荐利用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)

这种写法的优势:

  • 日志系统会自动处理格式化,性能更优
  • 日志框架能保留原始消息模板和参数,便于后续的日志分析或二次处理
  1. 验证日志文件:打开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
  1. 额外代码优化建议:
    • 路径拼接不要直接用+,改用os.path.join(directory, '*.png'),避免因目录末尾有无斜杠导致的路径错误
    • glob.glob的recursive=True在匹配*.png时无意义(该模式不会匹配子目录),可移除该参数

内容的提问来源于stack exchange,提问作者programmer_04_03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:12:07