Reputation: 605
What is the best way to convert a log string back to the LogRecord
that caused that string to be generated in the first place, provided that I have the formatter string.
I know I can use regex for this, but I was wondering if there's a better way to achieve this.
Formatter:
%(asctime)s--%(name)s--%(levelname)s--%(funcName)s:%(lineno)s---%(message)s
Sample:
2014-07-28 16:46:39,221--sys.log--DEBUG--hello:61---hello world
Regex:
^(?P<asctime>.*?)--(?P<name>.*?)--(?P<levelname>.*?)--(?P<funcName>.*?):(?P<lineno>.*?)---(?P<message>.*?)$
Regex example:
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()
Output:
{'name': 'sys.log', 'funcName': 'hello', 'lineno': '61', 'asctime': '2014-07-2816:46:39,221', 'message': 'hello world', 'levelname': 'DEBUG'}
References:
Upvotes: 1
Views: 852
Reputation: 26032
For this example, just split at the double-dashes:
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'}
Upvotes: 3