2020-03-05 22:51:21 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Global utility methods and classes."""
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
|
|
|
import colorama
|
|
|
|
from pythonjsonlogger import jsonlogger
|
|
|
|
|
2023-02-12 13:46:35 +00:00
|
|
|
from dockertidy.utils import Singleton, to_bool
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
CONSOLE_FORMAT = "{}[%(levelname)s]{} %(message)s"
|
2021-10-07 20:59:54 +00:00
|
|
|
JSON_FORMAT = "%(asctime)s %(levelname)s %(message)s"
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _should_do_markup():
|
|
|
|
py_colors = os.environ.get("PY_COLORS", None)
|
|
|
|
if py_colors is not None:
|
|
|
|
return to_bool(py_colors)
|
|
|
|
|
|
|
|
return sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
|
|
|
|
|
|
|
|
|
|
|
|
colorama.init(autoreset=True, strip=not _should_do_markup())
|
|
|
|
|
|
|
|
|
2023-02-12 13:46:35 +00:00
|
|
|
class LogFilter:
|
2020-03-05 22:51:21 +00:00
|
|
|
"""A custom log filter which excludes log messages above the logged level."""
|
|
|
|
|
|
|
|
def __init__(self, level):
|
|
|
|
"""
|
|
|
|
Initialize a new custom log filter.
|
|
|
|
|
|
|
|
:param level: Log level limit
|
|
|
|
:returns: None
|
|
|
|
|
|
|
|
"""
|
|
|
|
self.__level = level
|
|
|
|
|
|
|
|
def filter(self, logRecord): # noqa
|
|
|
|
# https://docs.python.org/3/library/logging.html#logrecord-attributes
|
|
|
|
return logRecord.levelno <= self.__level
|
|
|
|
|
|
|
|
|
|
|
|
class MultilineFormatter(logging.Formatter):
|
|
|
|
"""Logging Formatter to reset color after newline characters."""
|
|
|
|
|
|
|
|
def format(self, record): # noqa
|
2023-02-12 13:46:35 +00:00
|
|
|
record.msg = record.msg.replace("\n", f"\n{colorama.Style.RESET_ALL}... ")
|
2020-03-05 22:51:21 +00:00
|
|
|
return logging.Formatter.format(self, record)
|
|
|
|
|
|
|
|
|
|
|
|
class MultilineJsonFormatter(jsonlogger.JsonFormatter):
|
|
|
|
"""Logging Formatter to remove newline characters."""
|
|
|
|
|
|
|
|
def format(self, record): # noqa
|
|
|
|
record.msg = record.msg.replace("\n", " ")
|
|
|
|
return jsonlogger.JsonFormatter.format(self, record)
|
|
|
|
|
|
|
|
|
|
|
|
class Log:
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Base logging object."""
|
2020-03-05 22:51:21 +00:00
|
|
|
|
2022-08-21 22:08:31 +00:00
|
|
|
def __init__(self, level=logging.WARNING, name="dockertidy", json=False):
|
2020-03-05 22:51:21 +00:00
|
|
|
self.logger = logging.getLogger(name)
|
|
|
|
self.logger.setLevel(level)
|
|
|
|
self.logger.addHandler(self._get_error_handler(json=json))
|
2022-08-21 22:08:31 +00:00
|
|
|
self.logger.addHandler(self._get_warning_handler(json=json))
|
2020-03-05 22:51:21 +00:00
|
|
|
self.logger.addHandler(self._get_info_handler(json=json))
|
|
|
|
self.logger.addHandler(self._get_critical_handler(json=json))
|
|
|
|
self.logger.addHandler(self._get_debug_handler(json=json))
|
|
|
|
self.logger.propagate = False
|
|
|
|
|
|
|
|
def _get_error_handler(self, json=False):
|
|
|
|
handler = logging.StreamHandler(sys.stderr)
|
|
|
|
handler.setLevel(logging.ERROR)
|
|
|
|
handler.addFilter(LogFilter(logging.ERROR))
|
|
|
|
handler.setFormatter(
|
|
|
|
MultilineFormatter(
|
2020-03-06 21:39:32 +00:00
|
|
|
self.error(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL))
|
|
|
|
)
|
|
|
|
)
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
if json:
|
|
|
|
handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT))
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
2022-08-21 22:08:31 +00:00
|
|
|
def _get_warning_handler(self, json=False):
|
2020-03-05 22:51:21 +00:00
|
|
|
handler = logging.StreamHandler(sys.stdout)
|
2022-08-21 22:08:31 +00:00
|
|
|
handler.setLevel(logging.WARNING)
|
|
|
|
handler.addFilter(LogFilter(logging.WARNING))
|
2020-03-05 22:51:21 +00:00
|
|
|
handler.setFormatter(
|
|
|
|
MultilineFormatter(
|
2022-08-21 22:08:31 +00:00
|
|
|
self.warning(
|
|
|
|
CONSOLE_FORMAT.format(colorama.Fore.YELLOW, colorama.Style.RESET_ALL)
|
|
|
|
)
|
2020-03-06 21:39:32 +00:00
|
|
|
)
|
|
|
|
)
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
if json:
|
|
|
|
handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT))
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
|
|
|
def _get_info_handler(self, json=False):
|
|
|
|
handler = logging.StreamHandler(sys.stdout)
|
|
|
|
handler.setLevel(logging.INFO)
|
|
|
|
handler.addFilter(LogFilter(logging.INFO))
|
|
|
|
handler.setFormatter(
|
|
|
|
MultilineFormatter(
|
2020-03-06 21:39:32 +00:00
|
|
|
self.info(CONSOLE_FORMAT.format(colorama.Fore.CYAN, colorama.Style.RESET_ALL))
|
|
|
|
)
|
|
|
|
)
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
if json:
|
|
|
|
handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT))
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
|
|
|
def _get_critical_handler(self, json=False):
|
|
|
|
handler = logging.StreamHandler(sys.stderr)
|
|
|
|
handler.setLevel(logging.CRITICAL)
|
|
|
|
handler.addFilter(LogFilter(logging.CRITICAL))
|
|
|
|
handler.setFormatter(
|
|
|
|
MultilineFormatter(
|
2020-03-06 21:39:32 +00:00
|
|
|
self.critical(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL))
|
|
|
|
)
|
|
|
|
)
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
if json:
|
|
|
|
handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT))
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
|
|
|
def _get_debug_handler(self, json=False):
|
|
|
|
handler = logging.StreamHandler(sys.stderr)
|
|
|
|
handler.setLevel(logging.DEBUG)
|
|
|
|
handler.addFilter(LogFilter(logging.DEBUG))
|
|
|
|
handler.setFormatter(
|
|
|
|
MultilineFormatter(
|
2020-03-06 21:39:32 +00:00
|
|
|
self.critical(CONSOLE_FORMAT.format(colorama.Fore.BLUE, colorama.Style.RESET_ALL))
|
|
|
|
)
|
|
|
|
)
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
if json:
|
|
|
|
handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT))
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
|
|
|
def set_level(self, s):
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Set log level."""
|
2020-03-05 22:51:21 +00:00
|
|
|
self.logger.setLevel(s)
|
|
|
|
|
|
|
|
def debug(self, msg):
|
|
|
|
"""Format info messages and return string."""
|
|
|
|
return msg
|
|
|
|
|
|
|
|
def critical(self, msg):
|
|
|
|
"""Format critical messages and return string."""
|
|
|
|
return msg
|
|
|
|
|
|
|
|
def error(self, msg):
|
|
|
|
"""Format error messages and return string."""
|
|
|
|
return msg
|
|
|
|
|
2022-08-21 22:08:31 +00:00
|
|
|
def warning(self, msg):
|
|
|
|
"""Format warning messages and return string."""
|
2020-03-05 22:51:21 +00:00
|
|
|
return msg
|
|
|
|
|
|
|
|
def info(self, msg):
|
|
|
|
"""Format info messages and return string."""
|
|
|
|
return msg
|
|
|
|
|
|
|
|
def _color_text(self, color, msg):
|
|
|
|
"""
|
|
|
|
Colorize strings.
|
|
|
|
|
|
|
|
:param color: colorama color settings
|
|
|
|
:param msg: string to colorize
|
|
|
|
:returns: string
|
|
|
|
|
|
|
|
"""
|
2023-02-12 13:46:35 +00:00
|
|
|
return f"{color}{msg}{colorama.Style.RESET_ALL}"
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
def sysexit(self, code=1):
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Exit running program with given exit code."""
|
2020-03-05 22:51:21 +00:00
|
|
|
sys.exit(code)
|
|
|
|
|
|
|
|
def sysexit_with_message(self, msg, code=1):
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Exit running program with given exit code and message."""
|
2020-03-05 22:51:21 +00:00
|
|
|
self.logger.critical(str(msg))
|
|
|
|
self.sysexit(code)
|
|
|
|
|
|
|
|
|
|
|
|
class SingleLog(Log, metaclass=Singleton):
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Singleton logger object."""
|
|
|
|
|
2020-03-05 22:51:21 +00:00
|
|
|
pass
|