46

我正在尝试破译日志中包含的信息(日志记录设置使用默认格式化程序)。该文档指出:

对记录进行格式化 - 如果设置了格式化程序,请使用它。否则,使用模块的默认格式化程序。

但是,我找不到任何实际说明此默认格式的参考资料。

4

5 回答 5

72

默认格式位于此处,即:

BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"  

格式代码将告诉您如何自定义它。这是有关如何自定义它的一个示例。

import sys
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
    datefmt="%d/%b/%Y %H:%M:%S",
    stream=sys.stdout)

logging.info("HEY")

结果是:

[26/May/2013 06:41:40] INFO [root.<module>:1] HEY
于 2013-05-26T13:42:45.207 回答
7
import logging
print(logging.BASIC_FORMAT)

Old thread but this comes up first in my google search results for the query "python logging default format", so I thought I should add my answer.

Also some comments asked about how one could have come to discover this on their own. Here is a natural thing to do:

import logging
print(dir(logging))

BASIC_FORMAT is in there, in fact it is the first entry in the result in my case.

于 2017-04-06T17:32:12.300 回答
3

它的来源是logging/__init__.py

_defaultFormatter = Formatter()

默认格式字符串是%(message)s,它也在源代码中:

if fmt:
    self._fmt = fmt
else:
    self._fmt = "%(message)s"
于 2013-05-26T08:52:38.893 回答
2

默认似乎是%(levelname)s:%(name)s:%(message)s

import logging
logging.error("Some error")
print "fmt: " , logging.root.handlers[0].formatter._fmt
# ERROR:root:Some error
# fmt:  %(levelname)s:%(name)s:%(message)s
于 2013-05-26T09:35:38.420 回答
1

Here is the example of an advanced way of logging:-

import logging
class logger_con():
   def log_test(self):
      """
        :create logger
        :set logger level
        :create console handler
        :add formatter to console handler
        :add console handler to logger
        :add logging massage
        :return:
      """
    #create logger and set level
    logger=logging.getLogger(logger_con.__name__)

    logger.setLevel(logging.INFO)

    #create console handler(we are using steamHandler which is only used to display log in console)

    con_handler=logging.StreamHandler()
    con_handler.setLevel(logging.INFO)

    #create formatter and add formatter to con_handler
    formatter=logging.Formatter('%(asctime)s : %(message)s : %(levelname)s -%(name)s',datefmt='%d%m%Y %I:%M:%S %p')
    con_handler.setFormatter(formatter)
    #add console handler to logger
    logger.addHandler(con_handler)

    logger.debug('Program debugging')
    logger.info('massage conatain information')
    logger.warning('warning message')
    logger.error('massage contains error')
    logger.critical('critical massages')
于 2019-05-12T01:17:19.967 回答