简体   繁体   English

"使用 python 3.3.4 和 RotatingFileHandler 时出现 PermissionError"

[英]PermissionError when using python 3.3.4 and RotatingFileHandler

I am trying to get a rotating log file for a GUI application I am writing with python 3.3.4 and PyQt4.我正在尝试为我正在使用 python 3.3.4 和 PyQt4 编写的 GUI 应用程序获取旋转日志文件。

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')

Instead of adding handler to the logger object you can directly specify handler in basicConfig().您可以直接在 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.如果将 RotatingFileHandler 添加到记录器对象,则一个对象可能会打开日志文件,同时另一个对象可能会尝试重命名它,从而引发 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')

Spent half a day on this as non previous answer resolved my issue.花了半天时间,因为以前的答案解决了我的问题。

My working solution is to use https://pypi.org/project/concurrent-log-handler/ instead of RotatingFileHandler.我的工作解决方案是使用https://pypi.org/project/concurrent-log-handler/而不是 RotatingFileHandler。 In multiple thread scenarios like Flask app, PermissionError will be raised when we rotate the log file that reaches maximum size.在 Flask 应用程序等多线程场景中,当我们旋转达到最大大小的日志文件时,将引发 PermissionError。

Install pypiwin32 to get rid of No Module name win32con error.安装pypiwin32以摆脱No Module name win32con错误。

Thanks go to https://www.programmersought.com/article/43941158027/感谢访问https://www.programmersought.com/article/43941158027/

You cannot specify the same filename in both basicConfig() and RotatingFileHandler().您不能在 basicConfig() 和 RotatingFileHandler() 中指定相同的文件名。 I had this same issue and I removed the filename parameter from basicConfig() and it now works.我遇到了同样的问题,我从 basicConfig() 中删除了文件名参数,现在它可以工作了。

Check that the file isn't being kept open by eg Windows file indexing, anti-virus or other software.检查文件没有被例如 Windows 文件索引、防病毒软件或其他软件保持打开状态。 Files that are open can't be renamed.无法重命名打开的文件。

I changed the application to use dictConfig and created a separate file that holds the dictionary configuration.我将应用程序更改为使用 dictConfig 并创建了一个单独的文件来保存字典配置。 At the top of my main application I have:在我的主要应用程序的顶部,我有:

from log.logger import LOGGING

logging.config.dictConfig(LOGGING)
logger = logging.getLogger('testlogging')

Then in log.logger I have:然后在log.logger我有:

import logging
import sys
import resources

LOGGING = {
        "version":1,
        "handlers":{
                    "fileHandler":{
                        "class":"logging.handlers.RotatingFileHandler",
                        "formatter":"myFormatter",
                        "filename":resources.LOG_FILE_PATH,
                        "maxBytes":100000,
                        "backupCount":5
                        },
                    "console":{
                        "class":"logging.StreamHandler",
                        "formatter":"myFormatter"
                        }
                    },        
        "loggers":{
            "aoconnect":{
                "handlers":["fileHandler", "console"],
                "level":"DEBUG",
                }
            },

        "formatters":{
            "myFormatter":{
                "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
                }
            }
        }

This all seems to work pretty well.这一切似乎都运行良好。

In My case file size is full, after removing server.log file it worked在我的情况下文件大小已满,删除server.log文件后它工作

LOGS_DIR = os.path.join(BASE_DIR, 'logs')
LOGGING = {
    'version': 1,
    'handlers': {
    'log_file': {
        'level': 'INFO',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(LOGS_DIR, 'server.log'),
        'backupCount': 10, # keep at most 10 log files
        'maxBytes': 5*1024*1024 # 5242880 bytes (5MB)
        },
    },
    'loggers': {
        'django': {
            'handlers':['log_file'],
            'propagate': True,
            'level':'INFO',
        },
    },
}

In my case (Windows Server 2016 + IIS + FastCGI + Flask) finally I fix it by turning off files indexing in the folder.在我的情况下(Windows Server 2016 + IIS + FastCGI + Flask)最后我通过关闭文件夹中的文件索引来修复它。 how-to如何

Source: https://stackoverflow.com/a/22467917/9199668来源: https : //stackoverflow.com/a/22467917/9199668

Btw, it was working for months correctly... I have no idea why...顺便说一句,它正常工作了几个月......我不知道为什么......

In my case it happens only in Windows.就我而言,它只发生在 Windows 中。 To solve it I changed the delay<\/strong> parameter to True for my TimedRotatingFileHandler log handler.为了解决这个问题,我将 TimedRotatingFileHandler 日志处理程序的延迟<\/strong>参数更改为 True。

Docs -> https:\/\/docs.python.org\/3\/library\/logging.handlers.html#logging.handlers.TimedRotatingFileHandler<\/a>文档-> https:\/\/docs.python.org\/3\/library\/logging.handlers.html#logging.handlers.TimedRotatingFileHandler<\/a>

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM