You can not select more than 25 topics
Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
- #!/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
-
-
- # Format string
- FORMAT_STRING = '[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)d][%(funcName)s][%(name)s] %(message)s'
- 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
-
- if not ENABLE_LOG:
- logging.disable(logging.CRITICAL)
- else:
- logging.disable(logging.NOTSET)
- # Initialize configuration
- logging.basicConfig(format=FORMAT_STRING)
- if SAVE_LOG_FILE:
- # Save log information into file
- fileshandle = logging.handlers.RotatingFileHandler('my_log')
- # Set the default log level
- fileshandle.setLevel(DEFAULT_LEVEL)
- formatter = logging.Formatter(FORMAT_STRING)
- fileshandle.setFormatter(formatter)
- # Save log into file for the default root logger
- logging.getLogger('').addHandler(fileshandle)
- logging.getLogger('').setLevel(DEFAULT_LEVEL)
-
- Logger.get_instance()
-
- D = logging.debug
- I = logging.info
- E = logging.error
- W = logging.warning
- C = logging.critical
-
- class MyLogger():
- def __init__(self, name):
- self.__logger = logging.getLogger(name)
- self.__dict__['D'] = self.__logger.debug
- self.__dict__['I'] = self.__logger.info
- self.__dict__['E'] = self.__logger.error
- self.__dict__['W'] = self.__logger.warning
- self.__dict__['C'] = self.__logger.critical
-
- self.__logger.setLevel(logging.ERROR)
-
- 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()
-
- logger = MyLogger("mylogger")
- logger.D(f"Only test: {__name__}")
- logger.I(f"Only test: {__name__}")
- logger.E(f"Only test: {__name__}")
- logger.W(f"Only test: {__name__}")
- logger.C(f"Only test: {__name__}")
|