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

时间:2015-07-21 23:23:33

标签: python logging io m

我正在学习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):由于control-C事件导致的程序中止

而不是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)

2 个答案:

答案 0 :(得分: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.debug更改为logging.info(或logging.debuglogging.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)

答案 1 :(得分:0)

对于 CTRL + C 事件,请使用try - except来捕获KeyboardInterrupt例外。