python日志配置
python引入logging日志模块后,可以在代码中进行日志输出和记录,如下所示LoggerUtils对于日志做了一些格式初始化工作,然后对外暴露相关创建日志的方法createLogger;
CmdLogger为日志的功能的一个简单演示类,通过创建的cmdLoger可以灵活打印info\warn\erro等不同级别的日志。
#!/usr/local/bin/python3.7
import logging
######日志格式初始化及封装:
class LoggerUtils:
def __init__(self, name, path):
self.logger = logging.getLogger(name)
self.logger.setLevel(level = logging.INFO)
handler = logging.FileHandler(path)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def createLogger(name, path):
return LoggerUtils(name, path).logger
######日志打印实例类:
class CmdLogger:
cmdLoger = LoggerUtils.createLogger(__name__, "log/cmd.log")
@staticmethod
def logCmd(arguments, cmd):
cmdPara = []
for argob in arguments:
if arguments[argob] is not False and arguments[argob] is not None:
if (argob=='--index'):
cmdPara.append("{0}:{1}".format(argob, arguments[argob]))
elif arguments[argob] != 0:
cmdPara.append("{0}:{1}".format(argob, arguments[argob]))
CmdLogger.cmdLoger.info("[%s]参数如下:\n%s", cmd, cmdPara)