我是一个对称矩阵 2022-05-23 23:00 采纳率: 40%
浏览 22
已结题

python中logging的使用问题

首先我定义一个类:

import logging

class Logger():
    def __init__(self, logfile='output.log'):
        self.logfile = logfile
        self.logger = logging.getLogger(__name__)
        logging.basicConfig(
            format='[%(asctime)s] - %(message)s',
            datefmt='%Y_%m_%d %H:%M:%S',
            level=logging.INFO,
            filename=self.logfile
        )

    def info(self, msg, *args):
        msg = str(msg)
        if args:
            print(msg % args)
            self.logger.info(msg, *args)
        else:
            print(msg)
            self.logger.info(msg)

然后我在下面的代码中使用了上面这个类:

import Logger

for foo in range(0, 10):
    file_name = "./out/" + str(foo) + ".log"
    logger = Logger(file_name)
    logger.info(str(foo))

我期望的是得到名字为0~9共10个.log文件,并且每个文件中的内容就是名字本身,比如:
“5.log”文件中是“[2022_05_23 22:42:36] - 5”
“6.log”文件中是“[2022_05_23 22:42:36] - 6”

然而上述代码运行后却得到只有一个“0.log”文件,其中内容为:
[2022_05_23 22:42:36] - 0
[2022_05_23 22:42:36] - 1
[2022_05_23 22:42:36] - 2
[2022_05_23 22:42:36] - 3
[2022_05_23 22:42:36] - 4
[2022_05_23 22:42:36] - 5
[2022_05_23 22:42:36] - 6
[2022_05_23 22:42:36] - 7
[2022_05_23 22:42:36] - 8
[2022_05_23 22:42:36] - 9

请问我要如何解决该问题?

  • 写回答

1条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-05-24 03:16
    关注

    这样应该能达到你的要求了:

    class Logger():
        def __init__(self, logfile='output.log'):
            self.logfile = logfile
            self.logger = logging.getLogger(logfile)
            fh = logging.FileHandler(logfile, mode='w')
            lf = logging.Formatter('[%(asctime)s] - %(message)s')
            fh.setFormatter(lf)
            self.logger.addHandler(fh)
            logging.basicConfig(
                format='[%(asctime)s] - %(message)s',
                datefmt='%Y_%m_%d %H:%M:%S',
                level=logging.INFO,
                #filename=self.logfile
            )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 6月1日
  • 已采纳回答 5月24日
  • 创建了问题 5月23日

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加