【发布时间】:2022-01-06 10:57:20
【问题描述】:
我正在尝试使用日志记录模块来维护日志,但是一旦我启动脚本,它就会继续附加到当前日期日志文件中,而不是为第二天创建新文件。脚本 24 小时运行。我不知道该如何处理。
我的代码:
from datetime import date, datetime
import time
import logging
LogDirectory="D:\\Python_Collateral_Validation_Service\\Logs"
while True:
logfile=LogDirectory+"\\"+str(date.today().strftime("%d/%m/%Y")).replace("/", "")+".log"
print("log file name := ",logfile)
logging.basicConfig(filename = logfile, level=logging.INFO, format='%(asctime)s %(message)s')
logging.info("CollateralValidation-> CSV File Not Present")
time.sleep(90)
打印声明:
log file name := D:\Python_Collateral_Validation_Service\Logs\06012022.log
log file name := D:\Python_Collateral_Validation_Service\Logs\07012022.log
PS D:\Alok\CR06645_PythonCode_phase2>
日志文件只为 06012022 生成,但它也在为 07012022 写入。预期是 07012022.log 没有生成。
06012022.log 的输出
2022-01-06 16:11:53,480 CollateralValidation-> CSV File Not Present
2022-01-06 16:12:26,580 CollateralValidation-> CSV File Not Present
2022-01-06 16:15:00,987 CollateralValidation-> CSV File Not Present
2022-01-07 16:16:29,998 CollateralValidation-> CSV File Not Present
07012022 没有为上面最后一行生成
【问题讨论】:
-
让你的代码更简单:
strftime("%d/%m/%Y")).replace("/", "")->strftime("%d%m%Y")? -
@ThomasWeller 感谢您的建议!!
-
大多数人希望他们的日志文件按日期排序,所以 %Y%m%d 可能是更好的选择。