Python-With-Gtk-Template/src/utils/logger.py

62 lines
2.1 KiB
Python
Raw Normal View History

2020-05-08 00:38:06 +00:00
# Python imports
2022-12-11 20:52:09 +00:00
import os
import logging
2020-05-08 00:38:06 +00:00
2023-01-29 06:06:52 +00:00
# Lib imports
2020-05-08 00:38:06 +00:00
# Application imports
from .singleton import Singleton
2020-05-08 00:38:06 +00:00
2023-01-29 06:06:52 +00:00
class Logger(Singleton):
2022-06-14 23:19:21 +00:00
"""
Create a new logging object and return it.
:note:
NOSET # Don't know the actual log level of this... (defaulting or literally none?)
Log Levels (From least to most)
2020-05-08 00:38:06 +00:00
Type Value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
2022-06-14 23:19:21 +00:00
:param loggerName: Sets the name of the logger object. (Used in log lines)
:param createFile: Whether we create a log file or just pump to terminal
2020-05-08 00:38:06 +00:00
2022-06-14 23:19:21 +00:00
:return: the logging object we created
"""
2020-05-08 00:38:06 +00:00
2022-06-14 23:19:21 +00:00
def __init__(self, config_path: str, _ch_log_lvl = logging.CRITICAL, _fh_log_lvl = logging.INFO):
self._CONFIG_PATH = config_path
self.global_lvl = logging.DEBUG # Keep this at highest so that handlers can filter to their desired levels
self.ch_log_lvl = _ch_log_lvl # Prety much the only one we ever change
self.fh_log_lvl = _fh_log_lvl
def get_logger(self, loggerName: str = "NO_LOGGER_NAME_PASSED", createFile: bool = True) -> logging.Logger:
2020-05-08 00:38:06 +00:00
log = logging.getLogger(loggerName)
2022-06-14 23:19:21 +00:00
log.setLevel(self.global_lvl)
2020-05-08 00:38:06 +00:00
# Set our log output styles
fFormatter = logging.Formatter('[%(asctime)s] %(pathname)s:%(lineno)d %(levelname)s - %(message)s', '%m-%d %H:%M:%S')
cFormatter = logging.Formatter('%(pathname)s:%(lineno)d] %(levelname)s - %(message)s')
ch = logging.StreamHandler()
2022-06-14 23:19:21 +00:00
ch.setLevel(level=self.ch_log_lvl)
2020-05-08 00:38:06 +00:00
ch.setFormatter(cFormatter)
log.addHandler(ch)
if createFile:
2022-01-24 06:38:12 +00:00
folder = self._CONFIG_PATH
file = f"{folder}/application.log"
2020-05-08 00:38:06 +00:00
if not os.path.exists(folder):
os.mkdir(folder)
fh = logging.FileHandler(file)
2022-06-14 23:19:21 +00:00
fh.setLevel(level=self.fh_log_lvl)
2020-05-08 00:38:06 +00:00
fh.setFormatter(fFormatter)
log.addHandler(fh)
return log