一、介绍
简介︰
logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径等
快速使用:
此文件名为:log_demo.py
#1、导入logging包
import logging
#2、设置配置信息
logging.basicConfig(level=logging.INFO,format='%(asctime)s-&(name)s-%(levelname)s-%(message)s')
#3、定义日志名称getlogger
logger=logging.getLogger("log_demo")
#4、ifno,debug
logger.info("info")
logger.debug("debug")
logger.warning("warning")
二、 基本使用
2.1日志输出控制台或文件
此文件名为:log_file_demo.py
import logging
#输出控制台
#1、设置logger名称
logger=logging.getLogger("log_file_demo")
#2、设置log级别
logger.setLevel(logging.INFO)
#3、创建handler
fh_stream=logging.StreamHandle()
#写入文件
fh_file=logging.FileHandler("./test.log")
#4、设置日志级别
fh_stream.setLevel(logging. INFO)
fh_file.setLevel(logging. INFO)
#5、定义输出格式
formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s ')
fh_stream.setFormatter( formatter)
fh_file.setFormatter(formatter)
#6、添加handler
logger.addHandler(fh_stream)
logger.addHandler(fh_file)
#7、运行输出
logger.info( "this is a info")
logger.debug ( "this is a debugl ")
Format格式说明
三、封装工具类
此文件名为:LogUtil.py
import logging
from Config import Conf
import datetime
from config.Conf import ConfigYaml
#封装Log工具类
#定义日志级别的映射
log_l={
"info": logging.INFO,
"debug": logging.DEBUG,
"warning": logging.WARNING,
"ERROR": logging.ERROR
}
#1、创建类
class Logger:
#2、定义参数
#输出日志文件名称。Loggername,日志级别
def __init__(self,log_file,log_name,log_level):
self.log_file=log_file#扩展名
self.log_name=log_name#参数的传递
self.log_level=log_level#配置文件
#3、编写输出控制台或文件
#设置logger名称
self.logger=logging.getLogger(self.log_name)
#设置log级别
self.logger.setLevel(log_l[self.log_level])
#判断hanlders是否存在
if not self.logger.hanldes:
#输出控制台
fh_stream=logging.StreamHandle()
fh_stream.setLevel(log_l[self.log_level])
formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s ')
fh_stream.setFormatter( formatter)
fh_file.setFormatter(formatter)
#写入文件
fh_file=logging.FileHandler(self.log_file)
fh_file.setLevel(log_l[self.log_level])
#添加handler
self.logger.addHandler(fh_stream)
self.logger.addHandler(fh_file)
#1.初始化参数数据
#日志文件名称,日志文件级别
#日志文件名称= logs目录+当前时间+扩展名
#logs目录
log_path=Conf.get_log_path()
#当前时间
current_time=datetime.datetime.now().strftime("%Y-%m-%d")
#扩展名
log_extension=ConfigYaml().get_conf__log_extension()
logfile=os.path.join( log_path, current_time+log_extension)
#日志文件级别
loglevel=ConfigYaml().egt_conf_log()
#2、对外方法,初始log工具类,提供其他类使用
def my_log(log_name=__file__):
return Logger(log_file=logfile,log_name=log_name,log_level=loglevel).logger
if _name_"main__":
my_log( ).debug( "this is a debug"')
此文件名为:Conf.yml(与上一篇文章的代码不同,有新增内容)
BASE:
#log等级
log_level: "debug"
#扩展名
log_extension: ".log"
test:
url: ""http:/ /211.103.136.242:8064"
"
此文件名为Conf.py(与上一篇文章的代码不同,有新增内容)
import os
import YamlUtil import YamlReader
#1、获取项目基本目录
#获取当前项目的绝对路径
current = os.path.abspath(__file__)
#print(current)查看测试路径(全部路径)
BASE__DIR=os.path.dirname(os.path.dirname(current))
#print(BASE_DIR)查看测试路径
#定义config目录的路径
_cofig_path=BASE_DIR+os.sep+"config"
#定义conf.yml文件的路径
_config_file=_config_path+os.sep+"cof.yml"
#定义logs文件路径
_log_path = BASE_ DIR + os.sep + "logs"
def get_config_path():
return _config_path
def get_config_file():
return _config_file
def get_log_path():
return _log_path()
#2、读取配置文件
#创建类
class ConfigYaml:
#初始yaml读取配置文件
def __init__(self):
self.config=YamlReader(get_config_file)
#定义方法获取需要信息
def get_conf_url(self):
return self.config["BASE"]["test"]["url"]
def get_conf_log(self):
return self.config["BASE"]["log_level"]
def get_conf_log_extension(self):
return self.config["BASE"]["log_extension"]
if __name__=="__main__":
coonf_read=ConfigYaml()
#print(conf_read.get_conf_url())
print(conf_read.get_conf_log())
print(conf_read.get_conf_log_extension())