python下logging庫之shutdown

一種場景:python開發(fā)中使用logging庫記錄日志信息。在程序結(jié)束前需要將日志轉(zhuǎn)存到一個備份存儲并刪除現(xiàn)有日志。但是刪除日志時通常會報錯,錯誤如下:

python.exe test.py
Traceback (most recent call last):
  File "C:/Users/sunday/Desktop/test/test.py", line 58, in <module>
    os.remove(log_file)
PermissionError: [WinError 32] 另一個程序正在使用此文件,進(jìn)程無法訪問。: 'C:\\Users\\sunday\\Desktop\\test\\test.log'

無法刪除的原因就是logging沒有釋放日志文件的句柄,造成沒權(quán)限刪除。這時候logging庫的shutdown就派上用場。查看shutdown源碼可以看到shutdown就是用于程序退出前被使用。

def shutdown(handlerList=_handlerList):
    """
    Perform any cleanup actions in the logging system (e.g. flushing
    buffers).

    Should be called at application exit.
    """
    for wr in reversed(handlerList[:]):
        #errors might occur, for example, if files are locked
        #we just ignore them if raiseExceptions is not set
        try:
            h = wr()
            if h:
                try:
                    h.acquire()
                    h.flush()
                    h.close()
                except (OSError, ValueError):
                    # Ignore errors which might be caused
                    # because handlers have been closed but
                    # references to them are still around at
                    # application exit.
                    pass
                finally:
                    h.release()
        except: # ignore everything, as we're shutting down
            if raiseExceptions:
                raise
            #else, swallow

#Let's try and shutdown automatically on application exit...
import atexit
atexit.register(shutdown)

刪除日志文件前加上shutdown,完美退出。


logging.shutdown()
os.remove(log_file)

執(zhí)行:
python.exe test.py

進(jìn)程已結(jié)束,退出代碼 0
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容