loguru.parser¶
-
class
Parser
[source]¶ An object to more easily parse generated logs.
The
Parser
provide a set of handful methods likely to be used while parsing logs for post-processing.You should not instaniate a
Parser
by yourself, usefrom loguru import parser
instead.-
static
cast
(_dict, **kwargs)[source]¶ Convert values of a dict to others defined types.
This is a convenient function used to cast dict values resulting from parsed logs from
str
to a more appropriate type.Parameters: - _dict (
dict
) – The dict to which values type should be changed. - **kwargs – Mapping between keys of the input
_dict
and the function that should be used to convert the associated value.
Returns: dict
– A copy of the input dictionnary with values converted to the appropriate type.Example
>>> dico = {"some": "text", "num": "42", "date": "2018-09-12 22:23:24"} >>> parser.cast(dico, num=int, date=lambda t: datetime.strptime(t, "%Y-%m-%d %H:%M:%S") {'some': 'text', 'num': 42, 'date': datetime.datetime(2018, 9, 12, 22, 23, 24)}
- _dict (
-
static
parse
(file, pattern, *, chunk=65536)[source]¶ Parse raw logs to extract each entry as a
dict
.The logging format has to be specified as the regex
pattern
, it will then be used to parse thefile
and retrieve each entries based on the named groups present in the regex.Parameters: - file (
str
,pathlib.Path
orfile-like object
) – The path of the log file to be parsed, or alternatively an already opened file object. - pattern (
str
orre.Pattern
) – The regex to use for logs parsing, it should contain named groups which will be included in the returned dict. - chunk (
int
, optional) – The number of bytes read while iterating through the logs, this avoid having to load the whole file in memory.
Yields: dict
– The dict mapping regex named groups to matched values, as returned byre.Match.groupdict()
.Examples
>>> reg = r"(?P<lvl>[0-9]+): (?P<msg>.*)" # If log format is "{level.no} - {message}" >>> for e in parser.parse("file.log", reg): # A file line could be "10 - A debug message" ... print(e) # => {'lvl': '10', 'msg': 'A debug message'}
- file (
-
static