Python:停止脚本在控制台中生成输出,但不生成Logfile

时间:2018-03-31 17:38:11

标签: python logging

我有一个无限循环运行的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

2 个答案:

答案 0 :(得分:0)

实际上所有日志都保存在您的文件中。控制台输出与文件不同的原因是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

答案 1 :(得分:0)

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