当前位置:首页 >> 脚本专栏

Python日志器使用方法及原理解析

日志记录,监控,便于定位bug

Python日志器使用方法及原理解析

进行二次封装

import os
import logging
from scripts.handle_yaml import do_yaml
from scripts.handle_path import LOG_PATH

class HandleLog:
  def __init__(self, name=None):
    if name is None:
      self.my_logger = logging.getLogger("testcase")
    else:
      self.my_logger = logging.getLogger(name)
    self.my_logger.setLevel(do_yaml.get_data("log", "logger_level"))
    console_handler = logging.StreamHandler()
    console_handler.setLevel("WARNING")
    log_filename = os.path.join(LOG_PATH, do_yaml.get_data("log", "log_filename"))
    file_handler = logging.FileHandler(log_filename, encoding="utf-8")
    formater = logging.Formatter('%(asctime)s - [%(levelname)s] - [msg]: %(message)s - %(name)s - %(lineno)d')
    console_handler.setFormatter(formater)
    file_handler.setFormatter(formater)
    self.my_logger.addHandler(console_handler)
    self.my_logger.addHandler(file_handler)

  def get_logger(self):
    return self.my_logger

do_log = HandleLog()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。