mikes-backup-rotator/domain/Logger.py

65 lines
1.5 KiB
Python
Raw Normal View History

import logging
2023-03-27 20:12:37 -07:00
from logging.handlers import SysLogHandler
2023-03-27 19:59:45 -07:00
import sys
class Logger:
2023-03-27 19:59:45 -07:00
def __init__(self, name: str, debug: bool=False):
self.__name = name
2023-03-27 19:59:45 -07:00
self.__logger = logging.getLogger(self.__name)
2023-03-27 19:59:45 -07:00
if debug:
level = logging.DEBUG
else:
level = logging.INFO
self.__logger.setLevel(level)
2023-03-27 20:12:37 -07:00
formatter = logging.Formatter('[%(name)s][%(levelname)s] %(message)s')
formatter_full = logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] %(message)s')
# Console output / stream handler (STDOUT)
handler = logging.StreamHandler(
stream=sys.stdout
)
handler.setLevel(level)
handler.addFilter(lambda entry: entry.levelno <= logging.INFO)
handler.setFormatter(formatter_full)
self.__logger.addHandler(handler)
# Console output / stream handler (STDERR)
handler = logging.StreamHandler(
stream=sys.stderr
)
handler.setLevel(logging.WARNING)
handler.setFormatter(formatter_full)
self.__logger.addHandler(handler)
2023-03-27 19:59:45 -07:00
2023-03-27 20:12:37 -07:00
# Syslog handler
handler = SysLogHandler(
address="/dev/log"
)
2023-03-27 19:59:45 -07:00
handler.setLevel(level)
handler.setFormatter(formatter)
self.__logger.addHandler(handler)
2023-03-27 20:12:37 -07:00
2023-03-27 20:17:45 -07:00
# This is annoying inside cron
# self.debug("Test debug log")
# self.info("Test info log")
# self.warn("Test warn log")
# self.error("Test error log")
2023-03-27 20:12:37 -07:00
2023-03-27 19:59:45 -07:00
def debug(self, s):
2023-03-27 19:59:45 -07:00
self.__logger.debug(s)
def info(self, s):
2023-03-27 19:59:45 -07:00
self.__logger.info(s)
def warn(self, s):
2023-03-27 19:59:45 -07:00
self.__logger.warn(s)
def error(self, s):
2023-03-27 19:59:45 -07:00
self.__logger.error(s)