Commit 066fc8c4 authored by JOSSOUD Olivier's avatar JOSSOUD Olivier
Browse files

Logger. Better manage log level (INFO, WARN and ERROR)

parent f91ea3fa
......@@ -2,27 +2,52 @@ import sys
import configobj
import datetime
import os
import warnings
class Logger:
def __init__(self, config_parser: configobj.ConfigObj):
def __init__(self, config_parser: configobj.ConfigObj, object_id: str):
self.config = config_parser
self.log_dir = self.config["LOGGER"]["log_dir"]
self.__create_log_dir__()
self.__delete_old_files__()
self.object_id = object_id
def write(self, instrument: str, message: str) -> None:
def write(self, msg: str, level: str = "INFO", date_str: str = None, object_id: str = None, exception_type=Exception) -> None:
if object_id is None:
object_id = self.object_id
# Build the message string
now = datetime.datetime.now(tz=datetime.timezone.utc)
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
msg = "[" + now_str + "]"
if instrument != "":
msg += "[" + instrument + "]"
msg += " " + message + "\n"
sys.stdout.write(msg)
message = "[" + now_str + "] " + level + " [" + object_id + "]"
if date_str is not None:
message += "[" + date_str + "]"
message += " " + msg + "\n"
# Write log message in log file
with open(self.__get_current_file_path__(now), "a") as log_file:
log_file.write(msg)
log_file.write(message)
# Display log message in console, depending on level
if level == "INFO":
sys.stdout.write(message)
elif level == "WARN":
warnings.warn(message)
elif level == "ERROR":
raise exception_type(message)
else:
raise ValueError("Unknown message level: " + level)
def info(self, msg: str, date_str: str = None):
self.write(msg, level="INFO", date_str=date_str)
def warn(self, msg: str, date_str: str = None):
self.write(msg, level="WARN", date_str=date_str)
def error(self, msg: str, date_str: str = None, exception_type=Exception):
self.write(msg, level="ERROR", date_str=date_str, exception_type=exception_type)
def __get_current_file_path__(self, now: datetime.datetime) -> str:
file_name = now.strftime("%Y-%m-%d") + ".log"
......
......@@ -17,11 +17,11 @@ class LogConfig:
self.config = config_parser
# Logger
self.object_id = object_id
if log is None:
self.logger = logger.Logger(self.config)
self.logger = logger.Logger(self.config, self.object_id)
else:
self.logger = log
self.object_id = object_id
def get_config_parser() -> configobj.ConfigObj:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment