最近学了下python的定制类相关,发现可以封装类进行链式调用,于是对Log类进行了封装
from enum import Enum
import logging
class AppLog:
level = Enum('level',{'debug':logging.DEBUG,'info':logging.INFO,'warning':logging.WARNING,'error':logging.ERROR,'critical':logging.CRITICAL})
logger = None
lvl = None
def __init__(self,name):
self.logger = logging.getLogger(name)
self.logger.setLevel(logging.DEBUG)
self.setLogHandle()
def setLogHandle(self):
fhandler = logging.FileHandler('log/app.log','a','utf-8')
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
fhandler.setFormatter(formatter)
fhandler.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(logging.ERROR)
self.logger.addHandler(fhandler)
self.logger.addHandler(console)
def __getattr__(self,name):
if(name in ('debug','info','warn','error','critical')):
self.lvl = self.level[name].value
return self
else:
raise AttributeError('Attr not Correct')
def __call__(self,msg):
self.logger.log(self.lvl,msg)
代码中使用了两个handler,其中debug级别及以上的Log会通过FileHandler写入当前目录下log/app.log文件下,error级别及以上的Log则会通过系统输出(ext://sys.stdout)的streamHandler在控制台进行输出
使用方法:如下直接调用即可
AppLog('test').error('xxx fail')
输出格式:
2018-07-16 12:41:17,185 test ERROR xxx fail