python handler是什么【python handler 子类 实例】

598次阅读
没有评论

python

python handler说明

handler,包含在logging模块中的三个handler之一。Handler 能覆盖我们在使用中的大部分情况, 包括将日志记录到文件中、将日志上传指定服务器等等。

python handler的子类

(1)StreamHandler

将日志消息发送到一个 File like的流对象实例中。

(2)FileHandler

将日志记录到磁盘文件中。

(3)BaseRotatingHandler(FileHandler)

在项目中,为了避免日志文件过大,需要切割日志文件,BaseRotatingHandler 就是切割日志文件处理类的基类。

python handler实例

import json
from kafka import KafkaProducer
from kafka.errors import KafkaError
import logging
import datetime
 
 
class KafkaLoggingHandler(logging.Handler):
    """
    自定义logging.Handler模块,自定义将日志输出到指定位置(这里是输出到kafka)
    """
    def __init__(self, config=None, topic=None, name=""):
        super(KafkaLoggingHandler, self).__init__()
 
        if isinstance(config, dict) is False:
            raise ValueError("lack of kafka config parameters...")
        if isinstance(topic, str) is False:
            raise ValueError("lack of kafka topic parameters...")
        self.name = name
        self.config = config
        self.producer = KafkaProducer(**self.config)
        self.topic = topic
 
        # 实例化自定义的日志过滤器
        filter = KafkaLogFilter()
        self.addFilter(filter)
 
        # 实例化自定义的日志格式化对象
        json_format = JsonForMatter()
        self.setFormatter(json_format)
 
    @staticmethod
    def on_send_success(record_metadata):
        # 如果消息成功写入Kafka,broker将返回RecordMetadata对象(包含topic,partition和offset
        print("Success: [{}] send success".format(record_metadata))
 
    @staticmethod
    def on_send_error(excp):
        # 如果失败broker将返回error。这时producer收到error会尝试重试发送消息几次,直到producer返回error
        print("INFO " + "send info failed, cause: {}".format(excp))
 
    def emit(self, record):
        """
        重写logging.Handler的emit方法
        :param record: 传入的日志信息
        :return:
        """
        # 对日志信息进行格式化
        value = self.format(record)
        # 转成json格式,注意ensure_ascii参数设置为False,否则中文乱码
        value = json.dumps(value, ensure_ascii=False).encode("utf-8")
        future = self.producer.send(topic=self.topic, value=value)
        try:
            record_metadata = future.get(timeout=10)
            self.on_send_success(record_metadata)
        except KafkaError as e:
            self.on_send_error(e)

以上就是python handler的介绍,在涉及到logging模块时,我们会频繁的使用到handler的子类,大家可以在课后做一些资料的查阅。

(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-29发表,共计2196字。
新手QQ群:570568346,欢迎进群讨论 Python51学习