使用 python 3.3.4 和 RotatingFileHandler 时的 PermissionError [英] PermissionError when using python 3.3.4 and RotatingFileHandler

查看:53
本文介绍了使用 python 3.3.4 和 RotatingFileHandler 时的 PermissionError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取我正在使用python 3.3.4和PyQt4编写的GUI应用程序的旋转日志文件.

I am trying to get a rotating log file for a GUI application I am writing with python 3.3.4 and PyQt4.

我的主脚本中包含以下代码片段:

I have the following snippet of code in my main script:

import logging
import resources

logger = logging.getLogger('main.test')

def main():
    logger.setLevel(logging.DEBUG)

    fh = RotatingFileHandler(resources.LOG_FILE_PATH, maxBytes=500, backupCount=5)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)

    logger.addHandler(fh)
    logger.info('main')

我的maxBytes低,因此我可以测试旋转是否正常工作,事实并非如此.每当旋转日志时,我都会收到以下错误:

I have the maxBytes low so that I can test the rotating is working correctly, which it is not. I am getting the following error whenever the log should be rotated:

Traceback (most recent call last):
File "C:\Python33\lib\logging\handlers.py", line 73, in emit
self.doRollover()
File "C:\Python33\lib\logging\handlers.py", line 176, in doRollover
self.rotate(self.baseFilename, dfn)
File "C:\Python33\lib\logging\handlers.py", line 116, in rotate
os.rename(source, dest)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\myuser\\.logtest\\test.log.1'

并且没有任何记录.任何帮助深表感谢.谢谢

And nothing is logged. Any help is much appreciated. Thank you

推荐答案

您可以直接在basicConfig()中指定处理程序,而不是将处理程序添加到记录器对象.如果将RotatingFileHandler添加到记录器对象,则一个对象可能会打开日志文件,而另一个对象可能同时尝试重命名该文件,这会抛出PermissionError.

Instead of adding handler to the logger object you can directly specify handler in basicConfig(). If you add RotatingFileHandler to the logger object then one object might open the log file and another at the same time might try to rename it which throws the PermissionError.

下面的代码似乎运行得很好.

Below code seems to work pretty well.

import logging
import resources
from logging.handlers import RotatingFileHandler

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[RotatingFileHandler(filename=resources.LOG_FILE_PATH, maxBytes=500, backupCount=5)])
logger = logging.getLogger('main.test')

def main():
    logger.setLevel(logging.DEBUG)
    logger.info('main')

这篇关于使用 python 3.3.4 和 RotatingFileHandler 时的 PermissionError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆