将格式化日志字符串转换回LogRecord

1 投票
1 回答
732 浏览
提问于 2025-04-18 15:10

如何将一个日志字符串转换回最初生成这个字符串的LogRecord,前提是我有格式化字符串,这个方法是什么呢?

我知道可以用正则表达式来实现这个,但我在想有没有更好的方法。

格式化器:

%(asctime)s--%(name)s--%(levelname)s--%(funcName)s:%(lineno)s---%(message)s

示例:

2014-07-28 16:46:39,221--sys.log--DEBUG--hello:61---hello world

正则表达式:

^(?P<asctime>.*?)--(?P<name>.*?)--(?P<levelname>.*?)--(?P<funcName>.*?):(?P<lineno>.*?)---(?P<message>.*?)$

正则表达式示例:

import re
pattern = re.compile('^(?P<asctime>.*?)--(?P<name>.*?)--(?P<levelname>.*?)--(?P<funcName>.*?):(?P<lineno>.*?)---(?P<message>.*?)$')
print pattern.match('2014-07-28 16:46:39,221--sys.log--DEBUG--hello:61---hello world').groupdict()

输出:

{'name': 'sys.log', 'funcName': 'hello', 'lineno': '61', 'asctime': '2014-07-2816:46:39,221', 'message': 'hello world', 'levelname': 'DEBUG'}

参考资料:

  1. https://docs.python.org/2/library/logging.html
  2. https://docs.python.org/2/howto/logging.html

1 个回答

3

在这个例子中,只需要在两个连字符(--)的地方进行分割:

sample = '2014-07-28 16:46:39,221--sys.log--DEBUG--hello:61---hello world'
fields = ('asctime', 'name', 'levelname', 'funcName', 'message')
values = { k: v for k, v in zip(fields, sample.split('--', len(fields) - 1)) }
# and do some mending
values['funcName'], values['lineno'] = values['funcName'].split(':')
values['message'] = values['message'][1:]
>>> values
{'asctime': '2014-07-28 16:46:39,221',
 'funcName': 'hello',
 'levelname': 'DEBUG',
 'lineno': '61',
 'message': 'hello world',
 'name': 'sys.log'}

撰写回答