编程语言
首页 > 编程语言> > python中将日志输出代码

python中将日志输出代码

作者:互联网

import logging

from common.osinfo import OsInfo
from common.yaml_read import Yaml_Read


class Out_Log:

    def out_log(self,logger,log_path,log_file_name):
        log_dict = Yaml_Read().read_info_from_yaml("log")
        formater = logging.Formatter(log_dict["format"]) # 实例化日志格式对象
        log_file_path = OsInfo().get_project_abs_path(log_path)+"\\"+log_file_name+".log" # 得到日志文件绝对路径
        with open(log_file_path,'w') as f: #写入方式打开日志文件
            f.write("")#清空日志文件

        handler = logging.FileHandler(log_file_path,'a') #实例化日志输出对象, 追加方式打开日志文件
        handler.setFormatter(formater) # 设置日志输出格式
        handler.setLevel(log_dict["level"]) #设置日志输出级别
        logger.setLevel(log_dict["level"]) # 设置收集日志级别
        logger.addHandler(handler) # 设置日志输出
        return handler

    def remove_handler_from_logger(self,logger,handler):
        logger.removeHandler(handler)

if __name__=="__main__":
    ol= Out_Log()
    logger = logging.getLogger()
    handler = ol.out_log(logger,"输出路径","log.log")
    logger.debug("debug信息")
    logger.info("info信息")
    logger.warning("warning信息")
    ol.remove_handler_from_logger(logger,handler)

标签:中将,log,python,handler,file,path,日志,logger
来源: https://blog.csdn.net/m0_65472085/article/details/123198725