使用 python 日志记录每天创建新的日志文件 [英] Create new log file for everyday using python logging
问题描述
我的python代码可以很好地创建具有执行代码的名称和日期的日志文件-
My python code works fine to create a log file with name and date on which code was executed -
例如-
我今天运行代码,它将创建日志文件- logfile_2020-01-15.log
I run code today it will create log file - logfile_2020-01-15.log
我明天运行代码,它将创建日志文件- logfile_2020-01-16.log
等.
I run code tomorrow it will create log file - logfile_2020-01-16.log
and so on.
现在担心的是,如果我的代码执行今天开始并且可以连续运行8天.它应该创建8个日志文件-每天1个文件: logfile_2020-01-15.log至logfile_2020-01-23.log
Now the concern is, if my code execution is started today and it keeps on running for 8 days. It should create 8 log files - 1 file each day: logfile_2020-01-15.log to logfile_2020-01-23.log
但是这没有发生.启动代码时,它会继续登录同一文件: logfile_2020-01-15.log
.
But this is not happening. It keeps on logging in same file: logfile_2020-01-15.log
when the code was initiated.
请任何人可以帮助我修改代码-
Please can anyone help me modify code-
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()
推荐答案
我会稍微清理一下代码,然后用这种方式重新编写.轮换新日志,并在文件末尾附加日期/时间.
I would clean up the code a little bit and re-write it this way. New logs are rotated and appended the date/time at the end of the file.
>>> 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
根据您的情况,您需要将以下行更改为:
In your case, you would need to change the following line to:
fh = TimedRotatingFileHandler('/Documents/projects/python/testlog.log', when='midnight')
每5秒钟编写一次日志文件并模拟日志轮换.
Writing to log file and simulating log rotate every 5 seconds.
>>> 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
这篇关于使用 python 日志记录每天创建新的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!