我已经使用RotatingFileHandler
模块设置了一个python logging logging
并创建了一个字符串格式配置。这是我的测试脚本:
class ExceptionHandler :
def __init__ ( self ) :
self.log = self.setupLog ( "testlog" )
def setupLog (self, name) :
log = logging.getLogger(name)
logging.basicConfig(format="%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
#by setting our logger to the DEBUG level (lowest level) we will include all other levels by default
log.setLevel(logging.DEBUG)
#setup the rotating file handler to automatically increment the log file name when the max size is reached
log.addHandler( logging.handlers.RotatingFileHandler('%s.log' % name, mode='a', maxBytes=50000, backupCount=5) )
return log
if __name__ == "__main__" :
exceptionHandler = ExceptionHandler()
exceptionHandler.log.log( 20, "Successfully completed script!" )
我在testlog.log
文件中期待的是此输出;相反,这只是打印到stdout而不是我的文件:
INFO 2015-05-06 09:07:55,472 <module> 56 Successfully completed script!
我在我的文件中得到的只是以下内容而没有任何字符串格式:
Successfully completed script!
有没有人知道我的日志设置/配置有什么问题?
答案 0 :(得分:2)
您在控制台上看到了正确的结果,因为日志正从名为Logger
的新testlog
传播到仍在写入控制台的根记录器。此Logger
具有正确的格式设置
basicConfig
。
但是,您的新Handler
并未从basicConfig()
继承该配置,因为as the docs say,其所做的一切都是
通过使用默认Formatter创建StreamHandler并将其添加到根记录器来为日志系统执行基本配置。
您需要add the formatting to your handler。像这样:
#setup the rotating file handler to automatically increment the log file name when the max size is reached
file_handler = logging.handlers.RotatingFileHandler('%s.log' % name, mode='a', maxBytes=50000, backupCount=5)
file_handler.setFormatter(logging.Formatter(fmt="%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s"))
log.addHandler(file_handler)
N.B。如果您不想将消息传递给根记录器,请在log.propagate = False
功能中添加setupLog
答案 1 :(得分:1)
我通过更改格式化程序如何应用于日志记录处理程序来解决我的问题,如下所示:
def setupLog (self, name) :
log = logging.getLogger(name)
#by setting our logger to the DEBUG level (lowest level) we will include all other levels by default
log.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler('%s.log' % name, mode='a', maxBytes=50000, backupCount=5)
#logging.basicConfig(format="%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
handler.setFormatter( logging.Formatter( "%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s" ) )
#setup the rotating file handler to automatically increment the log file name when the max size is reached
log.addHandler( handler )
return log
答案 2 :(得分:-4)
在 log = logging.getLogger(name)*
之前尝试使用 logging.basicConfigdef setupLog (self, name) :
logging.basicConfig(format="%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
log = logging.getLogger(name)