【问题标题】:How can I save my log file in Python when the process is killed当进程被杀死时,如何在 Python 中保存我的日志文件
【发布时间】:2020-09-03 17:58:41
【问题描述】:

我正在学习 Python 中的logging 模块。

但是,如果我这样记录

logging.basicConfig(filename='mylog.log',format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG)

while 1:
    logging.debug("something")
    time.sleep(1)

并用 control-C 事件中断进程(或进程被杀死),我无法从日志文件中得到任何信息。

无论发生什么,我都可以保存最多的日志吗?

————

编辑

问题似乎变得更复杂了:

我在我的脚本中导入了 scipy、numpy、pyaudio,我得到了:

forrtl: error (200): program aborting due to control-C event

而不是KeyboardInterrupt

我读过这个问题:Ctrl-C crashes Python after importing scipy.stats

并将这些行添加到我的脚本中:

import _thread
import win32api
def handler(dwCtrlType, hook_sigint=_thread.interrupt_main):
    if dwCtrlType == 0: # CTRL_C_EVENT
        hook_sigint()
        return 1 # don't chain to the next handler
    return 0 # chain to the next handler

然后:

try:
    main()
except KeyboardInterrupt:
    print("exit manually")
    exit()

现在,如果我使用 ctrl+C,脚本会在没有任何信息的情况下停止。 print("exit manually") 没有出现。当然,没有日志。

已解决

一个愚蠢的错误! 我在工作目录为System32 时运行脚本并希望在脚本路径中找到日志。

我这样改变路线后,一切都很好。

logging.basicConfig(filename=os.path.dirname(sys.argv[0])+os.sep+'mylog.log',format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG)

【问题讨论】:

  • 在不知道如何配置记录器的情况下,很难判断是否应该得到任何输出?正如 BrianO 所指出的,logging.debug 默认情况下不记录。你提到了一个日志文件,但默认的日志输出是sys.stderr,而不是一个文件。
  • 使用 control-C 中断进程和终止进程之间也有很大区别。我不知道 Windows(您似乎正在使用它),但在例如*nix,有多种方法可以杀死进程(即可以向可能停止该进程的进程发送各种信号)。您需要更清楚您是在谈论 control-C(可以使用except KeyboardInterrupt 拦截)还是其他中断。
  • @Evert,我发现了我的愚蠢错误。感谢您的帮助!

标签: python logging io


【解决方案1】:

当您使用logging.debuglogging.info、...、logging.critical 登录时,您使用的是 root 记录器。我假设您没有做任何事情来配置您未显示的日志记录,因此您使用的是开箱即​​用的默认配置。 (这是通过第一次调用logging.debug 为您设置的,它调用logging.basicConfig())。

根记录器的默认记录级别为logging.WARNING(如https://docs.python.org/3/howto/logging.html#logging-basic-tutorial 中所述)。因此,您使用logging.debuglogging.info 记录的任何内容都不会出现:) 如果您将logging.debug 更改为logging.warning(或.error.error.critical),您看到日志输出.

要让您的代码按原样工作,请在循环之前将根记录器的日志记录级别设置为logging.DEBUG

import logging
import time

# logging.getLogger() returns the root logger
logging.getLogger().setLevel(logging.DEBUG)

while 1:
    logging.debug("something")
    time.sleep(1)

【讨论】:

    【解决方案2】:

    对于 CTRL + C 事件,使用try-except 来捕获KeyboardInterrupt 异常。

    【讨论】:

    • @PaleNeutron 你定义了handler 函数,但是之前的ctypes 调用和所有这些东西呢?另外,您为什么使用_thread 而不是thread?如果您的进程被杀死,您将无能为力。
    猜你喜欢
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多