#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
改进的日志类:
1. 使用format对象,就不用自己采集环境信息,库可以采集信息
2. 将多个handler绑定到一个logger上,且每个handler设置相应级别
日志会产生多份,每个handler只记录自己的级别和含高于自己级别的日志
3. 还是需要inspect库采集环境信息,因为logging的API被封装过了,
format只能采集直接调用logging模块API的函数信息
'''
import os
import sys
import time
import logging
import inspect
handlers = {logging.NOTSET:"/tmp/TNLOG-notset.log",
logging.INFO:"/tmp/TNLOG-info.log",
logging.DEBUG:"/tmp/TNLOG-debug.log",
logging.WARNING:"/tmp/TNLOG-warning.log",
logging.ERROR:"/tmp/TNLOG-error.log",
logging.CRITICAL:"/tmp/TNLOG-critical.log"}
def createHandlers():
logLevels = handlers.keys()
'''日志格式:[时间] [类型] [记录代码] 信息'''
fmt = '[%(asctime)s] [%(levelname)s] %(message)s '
formatter = logging.Formatter(fmt)
for level in logLevels:
path = os.path.abspath(handlers[level])
print path
handlers[level] = logging.FileHandler(path)
handlers[level].setLevel(level)
handlers[level].setFormatter(formatter)
#加载模块时创建全局变量
createHandlers()
class TNLog(object):
'''TNLog.constant'''
NOTSET = logging.NOTSET
INFO = logging.INFO
DEBUG = logging.DEBUG
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
def __init__(self,setLevel=logging.NOTSET):
self.__loggers = logging.getLogger()
logLevels = handlers.keys()
for level in logLevels:
self.__loggers.addHandler(handlers[level]) #将多个handler绑到一个logger上
self.__loggers.setLevel(setLevel)
def addCallingPointInfo(self,message):
frame,filename,lineNo,functionName,code,iUnknowField = inspect.stack()[2]
'''[文件名 - 行数 - 函数名] 信息'''
return "[%s - %s - %s] %s" %(filename,lineNo,functionName,message)
def info(self,message):
message = self.addCallingPointInfo(message)
self.__loggers.info(message)
def error(self,message):
message = self.addCallingPointInfo(message)
self.__loggers.error(message)
def warning(self,message):
message = self.addCallingPointInfo(message)
self.__loggers.warning(message)
def debug(self,message):
message = self.addCallingPointInfo(message)
self.__loggers.debug(message)
def critical(self,message):
message = self.addCallingPointInfo(message)
self.__loggers.critical(message)
#全局logger
logger = TNLog(TNLog.DEBUG)
def getLogger():
return logger
if __name__ == "__main__":
logger = getLogger()
logger.debug("debug")
logger = getLogger()
logger.info("info")
logger = getLogger()
logger.warning("warning")
logger = getLogger()
logger.error("error")
logger = getLogger()
logger.critical("critical")