|
- #!/usr/bin/env python3
- # -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil -*-
- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
-
- import logging
- import logging.handlers
-
- try:
- import colorlog
- SUPPORT_COLORFUL = True
- except:
- SUPPORT_COLORFUL = False
-
- """
- Just import the functions from this module and then invoke the concise functions to output log information:
-
- from logger import (D, I, E, C, W)
-
- # Output information of DEBUG level
- D("My DEBUG information")
- # Output information of WARNING level
- W("My WARNING information")
- """
-
- __all__ = ['C', 'D', 'E', 'I', 'W']
-
- # Globals
- DEFAULT_NAME = "donkey"
-
- # Format string: [time][log level name][filename:line number][function] message
- # Example: [2020-08-04 17:57:49,642][DEBUG][logger.py:60][test] log message
-
- COLOR_FORMAT_STRING = '{log_color}[{asctime}][{filename}:{lineno}][{funcName}] {message}'
- PLAIN_FORMAT_STRING = '[{asctime}][{levelname}][{filename}:{lineno}][{funcName}] {message}'
- ENABLE_LOG = True
- DEFAULT_LEVEL = logging.DEBUG
- SAVE_LOG_FILE = False
-
- # Create a singleton of logger
- class Logger():
- __instance = None
- @staticmethod
- def get_instance():
- """Static access method."""
- if Logger.__instance == None:
- Logger()
- return Logger.__instance
-
- def __init__(self):
- """Virtually private constructor."""
- if Logger.__instance != None:
- raise Exception("This class is a singleton!")
- else:
- Logger.__instance = self
- self.__logger = logging.getLogger(DEFAULT_NAME)
-
- if not ENABLE_LOG:
- logging.disable(logging.CRITICAL)
- else:
- # Initialize configuration
- if SUPPORT_COLORFUL:
- handler = colorlog.StreamHandler()
- handler.setFormatter(colorlog.ColoredFormatter(COLOR_FORMAT_STRING, style='{'))
-
- self.__logger.addHandler(handler)
- else:
- console = logging.StreamHandler()
- formatter = logging.Formatter(PLAIN_FORMAT_STRING, style="{")
- console.setFormatter(formatter)
- console.setLevel(DEFAULT_LEVEL)
- self.__logger.addHandler(console)
-
- if SAVE_LOG_FILE:
- # Save log information into file
- fileshandle = logging.handlers.RotatingFileHandler(DEFAULT_NAME)
- # Set the default log level
- fileshandle.setLevel(DEFAULT_LEVEL)
- formatter = logging.Formatter(PLAIN_FORMAT_STRING)
- fileshandle.setFormatter(formatter)
- # Save log into file for the default root logger
- self.__logger.addHandler(fileshandle)
- self.__logger.setLevel(DEFAULT_LEVEL)
- @property
- def logger(self):
- return self.__logger
-
- Logger.get_instance()
-
- D = Logger.get_instance().logger.debug
- I = Logger.get_instance().logger.info
- E = Logger.get_instance().logger.error
- W = Logger.get_instance().logger.warning
- C = Logger.get_instance().logger.critical
-
- if __name__ == '__main__':
- def test():
- D(f"Only test: {__name__}")
- I(f"Only test: {__name__}")
- E(f"Only test: {__name__}")
- W(f"Only test: {__name__}")
- C(f"Only test: {__name__}")
- test()
|