【问题标题】:Python: Stopping Script Generates Output in Console but not to LogfilePython:停止脚本在控制台中生成输出而不是到日志文件
【发布时间】: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

【问题讨论】:

标签: python logging


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 2020-09-24
      • 2018-07-12
      • 2018-02-05
      • 1970-01-01
      • 2012-05-28
      • 2021-07-03
      • 1970-01-01
      相关资源
      最近更新 更多