在python日志记录模块中,日志的格式如下:
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
**simple_example.py**
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
哪个输出如下:
输出:
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
我只是想知道是否有任何方法可以添加多个消息,而不是在末尾添加,例如
My custome message 1 - simple_example - DEBUG - my custom message 2
有什么办法可以格式化它:
formatter = logging.Formatter('%(message1)s - %(name)s - %(levelname)s - %(message2)s')
任何帮助将不胜感激
答案 0 :(得分:1)
您可以编写自己的Formatter类并将多余的消息作为kwargs传递:
import logging
class MyFormatter(logging.Formatter):
def format(self, record):
record.message2 = record.args.get("message2")
return super().format(record)
logger = logging.getLogger('test')
ch = logging.StreamHandler()
formatter = MyFormatter('%(asctime)s - %(message2)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
ch.setLevel(logging.ERROR)
logger.addHandler(ch)
logger.error("debug message", {"message2": "Blub"})
输出:
2019-02-08 14:33:50,487-模糊-测试-错误-调试消息
编辑:我不知道,为什么这在INFO级别下不能立即使用,但是您可以执行以下操作,这将起作用:
import logging
class MyFormatter(logging.Formatter):
def format(self, record):
record.message2 = record.args.get("message2")
return super().format(record)
logger = logging.getLogger('test')
ch = logging.StreamHandler()
ch.setFormatter(MyFormatter('%(asctime)s - %(message2)s - %(name)s - %(levelname)s - %(message)s'))
logging.basicConfig( level=logging.INFO, handlers=[ch] )
logger.info("debug message", {"message2": "Blub"})
输出:
2019-02-11 12:53:17,014-模糊-测试-信息-调试消息
编辑2:为了不使用 message2 来提供字典,您可以按以下方式更改代码:
import logging
class MyFormatter(logging.Formatter):
def format(self, record):
record.message2 = ""
if(record.args):
record.message2 = record.args.get("message2", "Fallback Value")
return super().format(record)
logger = logging.getLogger('test')
ch = logging.StreamHandler()
ch.setFormatter(MyFormatter('%(asctime)s - %(message2)s - %(name)s - %(levelname)s - %(message)s'))
logging.basicConfig( level=logging.INFO, handlers=[ch] )
logger.info("debug message", {"message2": "Blub"})
logger.info("This is my sample log")
logger.info("This is my sample log", {"hello": "World"})
输出:
2019-02-11 13:20:53,419 - Blub - test - INFO - debug message
2019-02-11 13:20:53,419 - - test - INFO - This is my sample log
2019-02-11 13:20:53,419 - Fallback Value - test - INFO - This is my sample log
答案 1 :(得分:-1)
您好,您可以直接在Formatter
中使用您的自定义消息,并使用%(message)s
来放置您的日志消息
请参见下面的示例
formatter = logging.Formatter('My custome message 1 - %(name)s - %(levelname)s - %(message)s my custom message 2')