利用单例模式实现日志文件分文件存储。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/11 23:21
# @Author : Zheng guoliang
# @Version : 1.0
# @File : log_util.py
# @Software: PyCharm
"""
1.需求功能:
利用单例模式将日志分文件存储
2.实现过程:
"""
import os
import sys
import time
import logging
import inspect
BASE_PATH = os.path.join(os.path.dirname(__file__), 'log')
if not os.path.exists(BASE_PATH):
os.mkdir(BASE_PATH)
handlers = {logging.NOTSET: "ZGL-notset.log",
logging.DEBUG: "ZGL-debug.log",
logging.INFO: "ZGL-info.log",
logging.WARNING: "ZGL-warning.log",
logging.ERROR: "ZGL-error.log",
logging.CRITICAL: "ZGL-critical.log"}
def create_handlers():
logLevels = handlers.keys()
for level in logLevels:
path = os.path.abspath(os.path.join(BASE_PATH, handlers[level]))
handlers[level] = logging.FileHandler(path)
class LogUtil(object):
__single = None
__loggers = None
def now_message(self):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
def __new__(cls, *args, **kwargs):
if cls.__single is None:
cls.__single = super().__new__(cls)
return cls.__single
def __init__(self, level=logging.NOTSET):
if self.__loggers is None:
self.__loggers = {}
create_handlers()
logLevels = handlers.keys()
for level in logLevels:
logger = logging.getLogger(str(level))
logger.addHandler(handlers[level])
logger.setLevel(level)
self.__loggers.update({level: logger})
def get_log_message(self, level, message):
frame, filename, lineNo, functionName, code, unknowField = inspect.stack()[2]
'''日志格式:[时间] [类型] [记录代码] 信息'''
return "[%s] [%s] [%s - %s - %s] %s" % (self.now_message(), level, filename, lineNo, functionName, message)
def info(self, message):
message = self.get_log_message("info", message)
self.__loggers[logging.INFO].info(message)
def error(self, message):
message = self.get_log_message("error", message)
self.__loggers[logging.ERROR].error(message)
def warning(self, message):
message = self.get_log_message("warning", message)
self.__loggers[logging.WARNING].warning(message)
def debug(self, message):
message = self.get_log_message("debug", message)
self.__loggers[logging.DEBUG].debug(message)
def critical(self, message):
message = self.get_log_message("critical", message)
self.__loggers[logging.CRITICAL].critical(message)
if __name__ == "__main__":
logger = LogUtil()
logger.debug("debug")
print(id(logger))
logger = LogUtil()
logger.info("info")
print(id(logger))
logger = LogUtil()
logger.warning("warning")
print(id(logger))
logger = LogUtil()
logger.error("error")
print(id(logger))
logger = LogUtil()
logger.critical("critical")
print(id(logger))