11

我目前有:

FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S', filename=LOGFILE, level=getattr(logging, options.loglevel.upper()))

...效果很好,但是我正在尝试做:

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'

即使MYVAR已定义,这也会引发 keyerrors。

有解决方法吗?MYVAR是一个常数,所以每次调用记录器时都必须传递它是一种耻辱。

谢谢!

4

4 回答 4

17

您可以使用自定义过滤器

import logging

MYVAR = 'Jabberwocky'


class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """
    def filter(self, record):
        record.MYVAR = MYVAR
        return True

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())

logger.warning("'Twas brillig, and the slithy toves")

产量

Jabberwocky 24/04/2013 20:57:31 - WARNING - 'Twas brillig, and the slithy toves
于 2013-04-25T00:49:39.940 回答
10

如前所述,您可以使用 custom Filterunutbu也可以使用LoggerAdapter

import logging

logger = logging.LoggerAdapter(logging.getLogger(__name__), {'MYVAR': 'Jabberwocky'})

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger.warning("'Twas brillig, and the slithy toves")

这使

Jabberwocky 25/04/2013 07:39:52 - 警告 - 'Twas brillig, and the slimy toves

或者,只需在每次调用时传递信息:

import logging

logger = logging.getLogger(__name__)

FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')

logger.warning("'Twas brillig, and the slithy toves", extra={'MYVAR': 'Jabberwocky'})

这给出了相同的结果。

由于 MYVAR 实际上是恒定的,因此该LoggerAdapter方法所需的代码比Filter您的情况下的方法少。

于 2013-04-25T06:42:18.527 回答
4

Borrowing from a comment above, I found that the simplest way to do this when the variable is static for all log entries is to simply include it in the formatter itself:

FORMAT = '{} %(asctime)s - %(levelname)s - %(message)s'.format(MYVAR)

With this method, no custom class implementation is required, and you don't have to worry about methods which are not defined for the various classes (LoggerAdapter and CustomAdapter), such as addHandler(). Admittedly, this is probably less Pythonic but it worked as a quick solution for me.

于 2018-05-30T21:29:25.243 回答
0
locals()
FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'

locals() 应该返回本地可用的所有变量的字典,然后返回错误。如果您在那里看不到它,那么它在本地不可用。这将证明它没有正确定义。我们需要更多代码来查看它是否定义不正确。或者,您可以尝试“globals()”来检查全局...。但您可能没有将“global MYVAR”放在输出 FORMAT 的定义中

于 2013-04-24T23:42:04.187 回答