当进程被终止时,如何将我的日志文件保存在 Python 中

How can I save my log file in Python when the process is killed

我正在学习 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)

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

当您使用 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.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)