我正在尝试创建一个记录器,每次执行代码时都会创建一个新的.log文件。 .log文件应具有以下格式info_24/03/2017_13:00:00.log
。我试图用strftime
来实现这一点,但是当我尝试运行代码时会出现错误。
#!/usr/bin/python3
import logging
from time import strftime
def main():
datestr = strftime('[%d/%m/%Y %T]')
logfile = 'info_{}.log'.format(strftime('%d/%m/%Y_%T'))
logformat = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(filename=logfile, filemode='w', level=logging.INFO, format=logformat, datefmt=datestr)
print('Hello world!')
logging.info('Program executed')
if __name__ == '__main__':
main()
当我从文件名中删除strftime
时,程序运行正常。显然,它没有达到预期的效果。否则,这是错误。
Traceback (most recent call last):
File "./log_example.py", line 16, in <module>
main()
File "./log_example.py", line 10, in main
logging.basicConfig(filename=logfile, filemode='w', level=logging.INFO, format=logformat, datefmt=datestr)
File "/usr/lib/python3.5/logging/__init__.py", line 1744, in basicConfig
h = FileHandler(filename, mode)
File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/home/estilen/Dropbox/College/Year_3/CSA2/Python/Examples/Logging/info_24/03/2017_13:04:29.log'
我知道旋转日志文件,但我想让它继续工作。如何修复代码以实现我的目标?
答案 0 :(得分:1)
你应该修改这一行:
logfile = 'info_{}.log'.format(strftime('%d/%m/%Y_%T'))
尝试将其替换为strftime('%d_%m_%Y_%T')
等其他字符。
不要在Linux中的文件名中使用/
。