Python的库非常强大,基本能找到我们所有需要的lib。logging模块是Python中的日志记录库,借鉴了Java中的LOG4J模块的思想,能非常方便的用于记录软件执行日志。
最近有在开发自动化测试工具,刚好需要logging模块,但在使用logging模块的RotatingFileHandler时,常抛出异常。打印类似于如下异常信息:
lne 86, in __init__
rotatingHandler.doRollover()
File "c:\python24\lib\logging\handlers.py", line 131, in doRollover
os.rename(self.baseFilename, dfn)
OSError: [Errno 13] Permission denied
查看日志文件权限后,发现文件属性全为问号,而对其执行copy或者move命令后,文件属性恢复正常。网上有说是在多个地方调用Getlogger之后导致的问题,排查发现并无其他多余模块获取了同样的Logger,暂时无解。(后来发现:存在多个线程通过logging直接记录日志到日志文件,多线程同时操作一个日志文件可能导致该错误) 随后google到一篇早期讨论帖才找到办法:
1、找到logging库下的handlers.py文件,定位到RotatingFileHandler的基类的doRollover方法,修改如下代码:
try:
os.rename(self.baseFilename, dfn)
#记得先import shutil,替换为:
try:
shutil.move(self.baseFilename, dfn)
2、可能导致日志记录操作异常,如出现如下异常(异常信息来自网络):
Traceback (most recent call last):
File "C:\Python24\lib\logging\handlers.py", line 72, in emit
self.doRollover()
File "C:\Python24\lib\logging\handlers.py", line 141, in doRollover
self.handleError(record)
NameError: global name 'record' is not defined
请尝试如下修改:
if self.shouldRollover(record):
self.doRollover()
#修改为:
if self.shouldRollover(record):
self.doRollover(record)
3、按Ctrl+C退出程序时,可能将打印如下异常:
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown
h.close()
File "C:\Python24\lib\logging\__init__.py", line 772, in close
StreamHandler.close(self)
File "C:\Python24\lib\logging\__init__.py", line 674, in close
del _handlers[self]
KeyError: <logging.handlers.RotatingFileHandler instance at 0x01E098A0>
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown
h.close()
File "C:\Python24\lib\logging\__init__.py", line 772, in close
StreamHandler.close(self)
File "C:\Python24\lib\logging\__init__.py", line 674, in close
del _handlers[self]
KeyError: <logging.handlers.RotatingFileHandler instance at 0x01E098A0>
请尝试如下修改:
_acquireLock()
try: #unlikely to raise an exception, but you never know...
del _handlers[self]
_handlerList.remove(self)
finally:
_releaseLock() #修改为:
_acquireLock()
try: #unlikely to raise an exception, but you never know...
#del _handlers[self]
if ( _handlers.has_key(self) ): del _handlers[self]
#if ( self in _handlerList ): _handlerList.remove(self)
_handlerList.remove(self)
finally:
_releaseLock()
原始讨论来自:http://www.44342.com/python-f871-t33115-p1.htm