logging 日志封装
作者:互联网
记录一种日志封装
logger.py
import os
import logging
class AppLogger:
def __init__(self, name, level=logging.DEBUG, stdout=False, tofile=None):
# 创建一个logger
self.logger = logging.Logger(name)
self.logger.setLevel(level)
# 定义日志输出格式
formatter = logging.Formatter('%(asctime)s [%(levelname)5s] %(filename)s:%(lineno)d %(message)s')
if tofile:
# 创建一个handler,用于写入日志文件
log_path = os.path.join(tofile)
fh = logging.FileHandler(log_path)
fh.setFormatter(formatter)
self.logger.addHandler(fh)
if stdout:
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setFormatter(formatter)
self.logger.addHandler(ch)
def getlog(self):
return self.logger
if __name__ == '__main__':
applog = AppLogger('applog', stdout=True).getlog()
applog.info('this is a info log')
引用
api.py
from logger import AppLogger
LOGLVL = logging.DEBUG
logger = AppLogger("autotest", LOGLVL, True, "migration.log").getlog()
logger.error('error, export file not found')
标签:__,封装,log,self,AppLogger,logging,日志,logger 来源: https://www.cnblogs.com/hanfe1/p/16630696.html