-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_utils.py
65 lines (51 loc) · 1.8 KB
/
log_utils.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
"""
Captures and stores logs from the application.
"""
import logging
import io
class StringIOHandler(logging.Handler):
"""
A custom logging handler that captures log messages in a StringIO object.
This allows capturing log messages in memory and later retrieving them.
"""
def __init__(self):
"""
Initializes the StringIOHandler by setting up the StringIO object.
"""
super().__init__()
self.log_capture_string = io.StringIO()
def emit(self, record):
"""
Writes a formatted log record to the StringIO object.
Args:
record (logging.LogRecord): The log record to be formatted and written.
"""
message = self.format(record)
self.log_capture_string.write(message + '\n')
def get_log_contents(self):
"""
Retrieves the contents of the log messages captured in the StringIO object.
Returns:
str: All log messages captured so far.
"""
return self.log_capture_string.getvalue()
def parse_validation_log(log):
"""
Parses a validation log to separate errors from warnings.
Args:
log (str): The log string containing validation messages.
Returns:
tuple: Two lists, one containing error messages and the other containing warning messages.
"""
errors = []
warnings = []
for line in log.split('\n'):
if 'error' in line.lower():
errors.append(line.strip())
elif 'warning' in line.lower():
warnings.append(line.strip())
return errors, warnings
# Create an instance of the custom log handler
log_handler = StringIOHandler()
# Configure the logging to use the custom handler and set the level to WARNING
logging.basicConfig(level=logging.WARNING, handlers=[log_handler])