/
logging.py
121 lines (99 loc) · 3.21 KB
/
logging.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""Utility functions for logging operations."""
__author__ = "Jeroen Van Der Donckt"
import logging
import warnings
import pandas as pd
from pathlib import Path
from typing import Union
def remove_inner_brackets(message: str) -> str:
"""Remove the inner brackets i.e., [ or ], from a string, outer brackets are kept.
Parameters
----------
message: str
The string to remove the inner brackets from.
Returns
-------
str:
A new message without any inner brackets.
"""
level = 0
new_message = ""
for char in message:
if char == "[":
if level == 0:
new_message += char
level += 1
elif char == "]":
if level == 1:
new_message += char
level -= 1
else:
new_message += char
assert level >= 0
return new_message
def delete_logging_handlers(logger: logging.Logger):
"""Delete all logging handlers that are not stream-handlers.
Parameters
----------
logger : logging.Logger
The logger.
"""
if len(logger.handlers) > 1:
logger.handlers = [
h for h in logger.handlers if type(h) == logging.StreamHandler
]
assert len(logger.handlers) == 1, "Multiple logging StreamHandlers present!!"
def add_logging_handler(
logger: logging.Logger, logging_file_path: Union[str, Path]
) -> logging.FileHandler:
"""Add a logging file-handler to the logger.
Parameters
----------
logger : logging.Logger
The logger.
logging_file_path : Union[str, Path]
The file path for the file handler.
Returns
-------
logging.FileHandler
The file-handler that is added to the given logger.
"""
if not isinstance(logging_file_path, Path):
logging_file_path = Path(logging_file_path)
if logging_file_path.exists():
warnings.warn(
f"Logging file ({logging_file_path}) already exists. "
f"This file will be overwritten!",
RuntimeWarning,
)
# Clear the file
# -> because same FileHandler is used when calling this method twice
open(logging_file_path, "w").close()
f_handler = logging.FileHandler(logging_file_path, mode="w")
f_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
f_handler.setLevel(logging.INFO)
logger.addHandler(f_handler)
return f_handler
def logging_file_to_df(logging_file_path: str) -> pd.DataFrame:
"""Parse the logged messages into a dataframe.
Parameters
----------
logging_file_path: str
The file path where the logged messages are stored.
Returns
-------
pd.DataFrame
A DataFrame containing the log_time, name, log_level and log message.
"""
column_names = ["log_time", "name", "log_level", "message"]
data = {col: [] for col in column_names}
with open(logging_file_path, "r") as f:
for line in f:
line = line.split(" - ")
for idx, col in enumerate(column_names):
data[col].append(line[idx].strip())
df = pd.DataFrame(data)
df["log_time"] = pd.to_datetime(df["log_time"])
return df