FileHandler编码生成异常

时间:2017-02-21 16:35:47

标签: python python-3.x logging encoding character-encoding

我有一个当前项目,它使用python日志库将日志输出到文件。我正在使用logging.handlers.RotatingFileHandler。出于某些奇怪的原因,当我将编码参数保留为默认值时(如此) file_handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=500000, backupCount=3)我得到一个跟踪如下(编辑):

--- Logging error ---
Traceback (most recent call last):
  File "%PYTHONPATH%\lib\logging\handlers.py", line 71, in emit
    if self.shouldRollover(record):
  File "%PYTHONPATH%\lib\logging\handlers.py", line 185, in shouldRollover
    self.stream = self._open()
  File "%PYTHONPATH%\lib\logging\__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
LookupError: unknown encoding: ascii
Call stack:
  File "%PATHTO%\MYCLASS.py", line 705, in __del__
    self.MyMethod()
  File "%PATHTO%\MYCLASS.py", line 1738, in disconnect
    self._log_message('Enter disconnect method.', logging.INFO)
  File "%PATHTO%\MYCLASS.py", line 1096, in _log_message
    self._logger.info(message)
Message: 'Enter MyMethod.'
Arguments: ()
--- Logging error ---
Traceback (most recent call last):
  File "%PYTHONPATH%\lib\logging\handlers.py", line 71, in emit
    if self.shouldRollover(record):
  File "%PYTHONPATH%\lib\logging\handlers.py", line 185, in shouldRollover
    self.stream = self._open()
  File "%PYTHONPATH%\lib\logging\__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
LookupError: unknown encoding: ascii
Call stack:
  File "%PATHTO%\MYCLASS.py", line 705, in __del__
    self.disconnect()
  File "%PATHTO%\MYCLASS.py", line 1760, in disconnect
    self._log_message('Exit disconnect method successfully.', logging.INFO)
  File "%PATHTO%\MYCLASS.py", line 1096, in _log_message
    self._logger.info(message)
Message: 'Exit MyMethod successfully.'
Arguments: ()

但是,如果我明确定义encoding ='UTF-8'或甚至编码='ASCII',则永远不会产生回溯。我甚至用小写的'ascii'打电话:file_handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=500000, backupCount=3, encoding='ascii')并没有例外。这是怎么回事?我怀疑这个问题与RotatingFileHandler编码默认为None类型和我在Windows上有关。但通常在没有编码的情况下打开文件从未产生错误。

我知道我的“问题”已经有了解决方案。只需明确定义我想要的任何编码。但我想更好地理解这种行为。

0 个答案:

没有答案