[英]Python: Stopping Script Generates Output in Console but not to Logfile
我有一个无限循环运行的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
实际上,所有日志都保存在文件中。 控制台输出与文件不同的原因是, traceback
后的部分不是日志的一部分,而是未捕获的异常(在这种情况下是由中断引起的)。
如果您也想将其保存到文件中,则需要使用try except
块来包围while循环,并将异常回溯打印到控制台文件和游览文件。
例如
import traceback
...
try:
// while loop
except KeyboardInterrupt as e:
// print traceback.format_exc and write it to your log file
except Exception as e:
// print traceback.format_exc and write it to your log file
try..except
块可以轻松捕获KeyboardInterrupt
异常。 这是有效的方法:
logging.info("=================================================")
logging.info("starting execution")
try:
while True:
pass
except KeyboardInterrupt:
logging.exception('KeyBoardInterrupt captured!')
raise
#Output:
03/31/18 14:25:20,344 root INFO =================================================
03/31/18 14:25:20,344 root INFO starting execution
03/31/18 14:25:22,003 root ERROR KeyBoardInterrupt captured!
Traceback (most recent call last):
File "bla.py", line 25, in <module>
pass
KeyboardInterrupt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.