【发布时间】:2018-04-01 02:27:29
【问题描述】:
我有一个 Python 脚本,它在无限循环中运行,可以在日志文件和控制台中生成日志。
如果我中断这个脚本(在 Pycharm 中),我只会在控制台日志中收到一些关于我手动中断的消息,而不是在日志文件中。
如何在日志文件中获得相同的输出?
脚本:
import logging
import os
my_log_file_name = os.path.basename(__file__) + ".my_log"
logging.basicConfig(filename=my_log_file_name,
filemode='a',
format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
datefmt='%D %H:%M:%S',
level=logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.info("=================================================")
logging.info("starting execution")
while True:
pass
日志文件中的输出:
03/31/18 19:27:34,335 root INFO =================================================
03/31/18 19:27:34,336 root INFO starting execution
控制台中的输出:
2018-03-31 19:27:34,335,335 root INFO =================================================
2018-03-31 19:27:34,336,336 root INFO starting execution
Traceback (most recent call last):
File "/home/user/4me/Technologie/0010-install/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1668, in <module>
main()
File "/home/user/4me/Technologie/0010-install/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/home/user/4me/Technologie/0010-install/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/user/4me/Technologie/0010-install/pycharm/2017-12-12-ultimate-edition/pycharm-2017.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/user/PycharmProjects/my_project/examples/my_script/attic.py", line 24, in <module>
pass
KeyboardInterrupt
【问题讨论】:
-
您可以为 Ctrl+C 创建一个信号处理程序并将其(代码帧)记录到日志文件中。例如:stackoverflow.com/questions/1112343/…