查看文章 |
如何用logging输出一条有用的日志
2009-02-10 10:21
平时logging模块我用得不多,不过在GAE上有时进行测试,我发现它可以输出执行的程序名。其实这一点并不困难,下面就是告诉你如何做。这里我今天在uliweb中修改的一段代码。 import logging log = None FORMAT = "%(levelname)-8s %(asctime)-15s %(filename)s,%(lineno)d] %(message)s" def get_logger(format=FORMAT, datafmt=None): global log handler = logging.StreamHandler() fmt = logging.Formatter(format, datafmt) handler.setFormatter(fmt) log = logging.getLogger('uliweb') log.addHandler(handler) log.setLevel(logging.INFO) return log if __name__ == '__main__': log = get_logger() log.error('This is an error %s', 'aaaa') log.warning('This is an warning') try: 1/0 except Exception, e: log.exception(e) 每个Handler可以设置自已的日志格式,上面我预定义了一个FORMAT,其中%(asctime)-15s用来输出日,精确到毫秒,%(filename)s 输出文件主名,%(lineno)d为执行的行号,%(message)是用来输出用户的日志。这些参数都是logging自带的,在logging.py中的Formatter类中的详细的描述: %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted 比文档好象详细多了。 上面的测试代码输出结果为: ERROR 2009-02-10 10:03:10,733 log.py,19] This is an error aaaa WARNING 2009-02-10 10:03:10,733 log.py,20] This is an warning ERROR 2009-02-10 10:03:10,733 log.py,24] integer division or modulo by zero Traceback (most recent call last): File "D:\project\svn\uliweb\uliweb\utils\log.py", line 22, in <module> 1/0 ZeroDivisionError: integer division or modulo by zero |
最近读者: