字面格式为format =“%(asctime)s-%(levelname)s-%(message)s”)

时间:2018-08-28 11:59:31

标签: python logging

我正在学习使用logging而不是print来调试我的代码:

In [89]: logging.basicConfig(level=logging.DEBUG, format=" %(asctime)s - %(levelname)s - %(message)s")
In [90]: logging.debug("Some debugging details.")
 2018-08-28 16:41:15,371 - DEBUG - Some debugging details.

我试图将格式重写为文字格式

In [5]: logging.basicConfig(level=logging.DEBUG, format=f" {(asctime)} - {(levelname)} - {(message)}")
NameError: name 'asctime' is not defined

In [5]: logging.basicConfig(level=logging.DEBUG, format=f" {(asctime)} - {(levelname)} - {(message)}")
-------------------------------------------------------------------------
In [6]: logging.basicConfig(level=logging.DEBUG, format=f" {(asctime)s} - {(levelname)s} - {(message)s}")
  File "<fstring>", line 1
    ((asctime)s)
              ^
SyntaxError: invalid syntax

是否可以编写format=" %(asctime)s - %(levelname)s - %(message)s"的文字格式?

1 个答案:

答案 0 :(得分:1)

否,这是不可能的,因为日志格式中的占位符名称由logging模块解释,而f字符串中的表达式由Python编译器本身解释,这不知道其含义logging模块只能理解的占位符名称。