Coverage for python/diagnostic_and_simulation_base/utility/logging.py: 74%
23 statements
« prev ^ index » next coverage.py v7.15.0, created at 2026-07-07 13:12 +0000
« prev ^ index » next coverage.py v7.15.0, created at 2026-07-07 13:12 +0000
1import datetime
2import logging
3import sys
5# Set the logging level.
6# Adjusting logging level changes what events are retained in the log.
7# Options from least to most verbose are:
8# * logging.CRITICAL
9# * logging.ERROR
10# * logging.WARNING
11# * logging.INFO
12# * logging.DEBUG
13# * logging.NOTSET
14logger = logging.getLogger("diagnostics_analysis_base")
15logger.setLevel(level=logging.DEBUG)
18class EmitLogToListHandler(logging.Handler):
19 """Custom handler to "emit" the log records into a list"""
21 def __init__(self, log_records: list[logging.LogRecord]) -> None:
22 self.log_records = log_records
23 logging.Handler.__init__(self)
25 def emit(self, record: logging.LogRecord) -> None:
26 self.log_records.append(record)
29class CustomFormatter(logging.Formatter):
30 """Custom format"""
32 def format(self, record: logging.LogRecord) -> str:
33 date_time = datetime.datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S")
34 filename_and_lineno = f"{record.filename}:{record.lineno}"
35 return f"{date_time} | {record.name} | {filename_and_lineno:<37} | {record.levelname} | {record.msg}"
38def format_logs(log_records: list[logging.LogRecord]) -> str:
39 """This converts a list of logging records into a string.
40 This is used to save the logging to MDSplus.
41 """
42 formatter = CustomFormatter()
43 str_output = ""
44 for log_record in log_records:
45 formatted_log = formatter.format(log_record)
46 str_output += formatted_log + "\n"
47 return str_output[0:-1]
50# def create_logger(log_name: str):
52# # Create an empty list where logs will be stored
53# log_records = []
55# # Create the logger
56# logger = logging.getLogger(log_name)
58# # Set the logging level. Adjusting this will change what events are retained in
59# # the log. Options from least to most verbose are:
60# # * logging.CRITICAL
61# # * logging.ERROR
62# # * logging.WARNING
63# # * logging.INFO
64# # * logging.DEBUG
65# # * logging.NOTSET
66# logger.setLevel(level=logging.DEBUG)
68# # Create and add handler to emit the logs to "stadnard out",
69# # i.e. printing to the terminal (standard behaviour)
70# handler_to_standard_out = logging.StreamHandler(sys.stdout)
71# handler_to_standard_out.setFormatter(CustomFormatter())
72# logger.addHandler(handler_to_standard_out)
74# # Create and add handler to emit the log "records" into the `log_records` list
75# handler_to_list = EmitLogToListHandler(log_records)
76# logger.addHandler(handler_to_list)
78# return logger, log_records