一般python使用日志功能
import logging
def logging_init():
app_name = "AppName"
log_file_name = "myapp_test.log"
logger = logging.getLogger(app_name)
format_str = "[%(asctime)s][%(levelname)s]> %(message)s"
formatter = logging.Formatter(format_str)
file_handler = logging.FileHandler(log_file_name)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(logging.INFO)
return logger
单例模式(一般采用)
import logging
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls,
*args, **kwargs)
return cls._instance
app_name = "appName"
log_file = "test.log"
class SingletonLogger(Singleton):
def __init__(self):
super(SingletonLogger, self).__init__()
self.logger = logging.getLogger(app_name)
format_str = "[%(asctime)s][%(levelname)s]> %(message)s"
formatter = logging.Formatter(format_str)
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
self.logger.setLevel(logging.INFO)
def debug(self, data):
self.logger.debug(data)
def info(self, data):
self.logger.info(data)
def warning(self, data):
self.logger.warning(data)
def error(self, data):
self.logger.error(data)
def test_log():
logger = SingletonLogger()
#output the log msg
logger.debug("this is the debug message")
logger.info("this is the info message")
logger.warning("this is the warning message")
logger.error("this is the error message")