【问题标题】:python logging not printing datetime and other format valuespython日志记录不打印日期时间和其他格式值
【发布时间】:2013-09-03 13:56:08
【问题描述】:

我正在尝试使用 python 日志记录模块为我的程序创建一个RotatingFileHandler。我的日志处理程序将输出记录到文件:/var/log/pdmd.log,基本功能似乎可以正常工作并根据需要记录输出。

但是,我正在尝试使用这种格式来格式化我的日志字符串:

"%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s"

但只有异常的message 部分被记录。这是我设置记录器的代码:

#class variable declared at the beginning of the class declaration
log = logging.getLogger("PdmImportDaemon")

def logSetup(self):
    FORMAT = "%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s"
    logging.basicConfig(format=FORMAT)

    #logging.basicConfig(level=logging.DEBUG)
    self.log.setLevel(logging.DEBUG) #by setting our logger to the DEBUG level (lowest level) we will include all other levels by default
    #setup the rotating file handler to automatically increment the log file name when the max size is reached
    self.log.addHandler( logging.handlers.RotatingFileHandler('/var/log/pdmd.log', mode='a', maxBytes=50000, backupCount=5) )

现在,当我运行一个方法并使用以下代码使程序输出到日志时:

 def dirIterate( self ):
    try:
        raise Exception( "this is my exception, trying some cool output stuff here!")               
    except Exception, e:
        self.log.error( e )
        raise e

pdmd.log 文件中的输出只是异常文本,没有其他内容。由于某种原因,格式没有得到尊重;我预计:

 ERROR 2013-09-03 06:53:18,416 dirIterate 89 this is my exception, trying some cool output stuff here!

关于为什么我在logging.basicConfig 中设置的格式没有得到尊重的任何想法?

【问题讨论】:

    标签: python exception logging formatting


    【解决方案1】:

    您也必须将格式添加到处理程序中。

    当您运行basicConfig() 时,您正在为root Logger 配置一个新的处理程序。
    在这种情况下,您的自定义处理程序没有格式。

    替换

    self.log.addHandler( logging.handlers.RotatingFileHandler('/var/log/pdmd.log', mode='a', maxBytes=50000, backupCount=5) )
    

    与:

    rothnd = logging.handlers.RotatingFileHandler('/var/log/pdmd.log', mode='a', maxBytes=50000, backupCount=5)
    rothnd.setFormatter(logging.Formatter(FORMAT))
    self.log.addHandler(rothnd)
    

    【讨论】:

    • 我按照你的建议做了,我得到了以下回溯:Traceback (most recent call last): File "pdmd.py", line 195, in <module> prog = ProgramHandler() File "pdmd.py", line 37, in __init__ self.logSetup() File "pdmd.py", line 55, in logSetup rothnd.format( FORMAT ) File "/usr/lib/python2.7/logging/__init__.py", line 723, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 464, in format record.message = record.getMessage() AttributeError: 'str' object has no attribute 'getMessage'
    • 对不起,我的错误,我修正了这个例子。
    • 哈哈我知道问题出在哪里,当你修复它时,我正在编辑你的帖子!谢谢!
    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2012-01-12
    • 2013-12-15
    • 2012-11-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多