Ошибка опрокидывания при входе из нескольких модулей в один файл журнала - PullRequest
0 голосов
/ 17 октября 2019

У меня есть пакет Python, в котором есть основной скрипт (main.py) и другой модуль (apirequests.py). Основной скрипт вызывает дочерний модуль для выполнения запросов REST API.

Для ведения журнала я инициировал обработчик вращающегося файла журнала размером 10 КБ в функции внутри init .py:

import logging
from logging.handlers import RotatingFileHandler

try:
    from http.client import HTTPConnection  # py3
except ImportError:
    from httplib import HTTPConnection  # py2

def setup_logger(name=__name__, log_file=None, level=logging.INFO):
    formatter = logging.Formatter('%(asctime)s: %(name)s: [%(levelname)s]: %(message)s')
    handler = RotatingFileHandler(log_file, maxBytes=10*1024, backupCount=5)
    handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)
    logger.propagate = True

    return logger

Я пытаюсь записать сообщения из файла main.py и apirequests.py в один файл журнала (log.log) и все сообщения HTTP-запроса в отдельный файл журнала (localhost.log).

но выполнение прерывается всякий раз, когда файл log.log пытается выполнить ролловер, потому что он пытается это сделать, пока один из модулей в пакете все еще пытается записать в него.

Вот как main.py вызывает функцию ведения журнала:

logger = setup_logger(__name__, log.log)

logger.info('Program begins') # This goes to Log.log file
.
.
.call apirequests() module's functions
.
.

Вот как apirequests.py вызывает средство ведения журнала:

logger1 = setup_logger(__name__, log.log)
logger2 = setup_logger('urllib3', localhost.log, logging.DEBUG)

logger1.info('Start making REST calls')  # # This goes to log.log file
.
.
<make some REST API calls whose logging goes to localhost.log file>
.
.

ОШИБКА :

  File "C:\Python27\Lib\logging\handlers.py", line 77, in emit
    self.doRollover()
  File "C:\Python27\Lib\logging\handlers.py", line 142, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file main.py, line 105
Traceback (most recent call last):
  File "C:\Python27\Lib\logging\handlers.py", line 77, in emit
    self.doRollover()
  File "C:\Python27\Lib\logging\handlers.py", line 142, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file apirequests.py, line 102
Traceback (most recent call last):
  File "C:\Python27\Lib\logging\handlers.py", line 77, in emit
    self.doRollover()
  File "C:\Python27\Lib\logging\handlers.py", line 142, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file apirequests.py, line 103 ```


...