鱼C论坛

 找回密码
 立即注册
查看: 1420|回复: 3

[已解决]说不清楚,展开看吧,代码不到30行

[复制链接]
发表于 2022-5-23 22:56:10 | 显示全部楼层 |阅读模式
60鱼币
首先我定义一个类:
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


请问我要如何解决该问题?
最佳答案
2022-5-23 22:56:11
我是一个椭圆 发表于 2022-5-24 11:58
已解决:

我是来收赏金的

最佳答案

查看完整内容

我是来收赏金的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-23 22:56:11 From FishC Mobile | 显示全部楼层    本楼为最佳答案   
我是一个椭圆 发表于 2022-5-24 11:58
已解决:

我是来收赏金的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-5-24 11:58:03 | 显示全部楼层
已解决:
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
        )
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-5-24 17:41:22 | 显示全部楼层

哈哈哈,那你来的真是时候
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-9 09:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表