【问题标题】:Create new log file for everyday using python logging使用 python 日志记录为每天创建新的日志文件
【发布时间】:2020-01-15 22:53:45
【问题描述】:

我的 python 代码可以很好地创建一个日志文件,其中包含执行代码的名称和日期 -

例如-

我今天运行代码它会创建日志文件 - logfile_2020-01-15.log

我明天运行代码,它将创建日志文件 - logfile_2020-01-16.log 等等。

现在的问题是,如果我的代码从今天开始执行并持续运行 8 天。它应该创建 8 个日志文件 - 每天 1 个文件:logfile_2020-01-15.log to logfile_2020-01-23.log

但这并没有发生。启动代码时,它会继续登录同一文件:logfile_2020-01-15.log

谁能帮我修改代码-

import datetime
import logging
import schedule
class Workflow:    

    def setupLoggingToFile():
        logFilePath = "C:\ExceptionLogFiles\"
        logdate = datetime.datetime.now().strftime('%Y-%m-%d')
        logging.basicConfig(
            format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d-%y %H:%M:%S',
            level=logging.DEBUG,
            handlers=[RotatingFileHandler(logFilePath + "logfile_"+logdate+".log",maxBytes=10485760, backupCount=100)])   

    def StartWorkflow(self):
        try:
            print("New Cron Cycle Started..")
        except Exception:
            logging.exception("Something went wrong.", exc_info=True)

    def StartCron(self):
        try:
            schedule.every(5).seconds.do(self.StartWorkflow)
            while 1:
                schedule.run_pending()
                time.sleep(1)
        except Exception:
            logging.debug("CRON was unable to start. Something Wrong in StartCron function.")
            logging.exception("CRON was unable to start. Something Wrong in StartCron function.", exc_info=True)


A = Workflow()
A.StartCron()

【问题讨论】:

  • 代码中缺少的一些东西。 1)您忘记在 setupLoggingToFile 中包含“self”。 2) RotatingFileHandler 仅在达到一定大小后才轮换日志,在您的情况下为 maxBytes = 10485760。您应该使用 TimedRotatingFileHandler 并将其设置为午夜。见docs.python.org/3/library/logging.handlers.html。 3) 为什么 handlers 是一个列表?

标签: python python-3.x logging


【解决方案1】:

我会稍微清理一下代码并以这种方式重新编写它。新日志会轮换并在文件末尾附加日期/时间。

>>> def logSetup ():
...    logger = logging.getLogger('testlog')
...    logger.setLevel(logging.DEBUG)
...    formatter = logging.Formatter(fmt='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
...                                  datefmt='%m-%d-%y %H:%M:%S')
...    fh = TimedRotatingFileHandler('/Documents/projects/python/testlog.log', when='S', interval=5)
...    fh.setFormatter(formatter)
...    logger.addHandler(fh)
...    return logger

在您的情况下,您需要将以下行更改为:

fh = TimedRotatingFileHandler('/Documents/projects/python/testlog.log', when='midnight')

写入日志文件并模拟日志每 5 秒轮换一次。

>>> for i in range (20):
...    logger.debug('%d Writing some logs' % i)
...    sleep (1)
...

结果变成:

$ cat testlog.log.2020-01-15_18-35-01
01-15-20 18:36:24 testlog      DEBUG    0 Writing some logs
01-15-20 18:36:25 testlog      DEBUG    1 Writing some logs
01-15-20 18:36:26 testlog      DEBUG    2 Writing some logs
01-15-20 18:36:27 testlog      DEBUG    3 Writing some logs
01-15-20 18:36:28 testlog      DEBUG    4 Writing some logs
$ cat testlog.log.2020-01-15_18-36-24
01-15-20 18:36:29 testlog      DEBUG    5 Writing some logs
01-15-20 18:36:30 testlog      DEBUG    6 Writing some logs
01-15-20 18:36:31 testlog      DEBUG    7 Writing some logs
01-15-20 18:36:32 testlog      DEBUG    8 Writing some logs
01-15-20 18:36:33 testlog      DEBUG    9 Writing some logs
$ cat testlog.log.2020-01-15_18-36-29
01-15-20 18:36:34 testlog      DEBUG    10 Writing some logs
01-15-20 18:36:35 testlog      DEBUG    11 Writing some logs
01-15-20 18:36:36 testlog      DEBUG    12 Writing some logs
01-15-20 18:36:37 testlog      DEBUG    13 Writing some logs
01-15-20 18:36:38 testlog      DEBUG    14 Writing some logs
$ cat testlog.log.2020-01-15_18-36-34
01-15-20 18:36:39 testlog      DEBUG    15 Writing some logs
01-15-20 18:36:40 testlog      DEBUG    16 Writing some logs
01-15-20 18:36:41 testlog      DEBUG    17 Writing some logs
01-15-20 18:36:42 testlog      DEBUG    18 Writing some logs
01-15-20 18:36:43 testlog      DEBUG    19 Writing some logs
$ cat testlog.log
01-15-20 18:36:39 testlog      DEBUG    15 Writing some logs
01-15-20 18:36:40 testlog      DEBUG    16 Writing some logs
01-15-20 18:36:41 testlog      DEBUG    17 Writing some logs
01-15-20 18:36:42 testlog      DEBUG    18 Writing some logs
01-15-20 18:36:43 testlog      DEBUG    19 Writing some logs

【讨论】:

  • 另外,只是好奇,日志文件是使用命名创建的:testlog.log.2020-01-15_18-35-01。是否可以创建如下命名:testlog_2020-01-15_18-35-01.log
  • 将时间附加到文件末尾是一种非常普遍的做法和行业标准,但我猜对于 Windows 来说它是不同的。不幸的是, TimedRotatingFileHandler 没有给你这样的选择。它在库中被硬编码。一个肮脏的 hack 会给你的日志文件一个名称,如 testlog(不带 .log),让文件处理程序附加后缀,用下划线替换文件名中的句点,最后返回并在末尾添加“.log”文件。
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
相关资源
最近更新 更多