python日志模块的日志处理程序,将所有日志发送到特定的redis通道
redis-log-handler的Python项目详细描述
redis日志处理程序
将日志传递到redis的标准logging
模块的处理程序。
安装
这是专门针对Python3.6.7开发的,但我不认为它会破坏版本。
开发
设置本地环境变量REDIS_HOST
以指向运行redis的主机。
$ export REDIS_HOST=localhost
安装开发要求
$ pip install -r requirements-dev.txt
如何使用
您可以将日志发布到一个通道,rpush
它们通过一个可选的ttl
键发布到一个密钥上。
或者通过从基类派生实现所需的行为。
向python记录器添加处理程序非常简单:
importloggingfromredis_log_handlerimportRedisKeyHandlerexample_handler=RedisKeyHandler('example_key')# Default parameters for Redis connection are usedlogger=logging.getLogger()# No name gives you the root loggerlogger.setLevel("WARNING")logger.addHandler(example_handler)logger.warning("This will rpush this message to the 'example_key' in Redis.")
配置redis连接
默认情况下,每个处理程序都将创建一个StrictRedis
实例,将每个参数从它们的__init__(**kwargs)
传递给strictredis实例化。
这意味着您可以根据需要将连接配置为特定的,但是每个参数都应该提供关键字;Handler(host=localhost)
,而不是Handler(localhost)
。
所有可用的配置选项都在tepython-redis documentation中可用。
handler=RedisKeyHandler("key",host="localhost",port=6379,password=None)connection_pool=redis.ConnectionPool(host="localhost")handler=RedisKeyHandler("key",connection_pool=connection_pool)
配置消息日志
每个处理程序都有raw_logging
选项,可以选择性地提供。
从初始化中省略它,将默认为False
,这意味着正在记录的消息将纯粹是发送的消息。
如果将其设置为True
,首先将记录内容,然后将其附加到行号,最后是路径名。
pure_handler=RedisKeyHandler("key_name")raw_handler=RedisKeyHandler("other_key_name",raw_logging=True)...logging.info("Test message")
pure_handler
将发出如下消息:Test message.
,
raw_handler
将发出如下消息:Test message. - 2: /.../file.py
。
一。redischannelhandler
这将打开到redis频道的连接,允许订阅者实时接收新消息。 日志实例触发的每个消息都将发布到指定的通道。
handler=RedisChannelHandler("channelname")
2.rediskeyhandler
这将创建/推送到提供的键上,无论日志实例将发出什么消息。
默认情况下,每条消息都将通过rpush
发送,因此当使用lrange $key 0 -1
检索列表时,所有消息都将按发送顺序返回。
可选地,可以提供一个ttl
(生存时间),它将是一个计数器,每次发送消息时都将设置,实际上是刷新此密钥生存时间的持续时间。
handler=RedisKeyHandler("some_key_name",ttl=60)
三。自定义redis处理程序
我们还提供了编写自定义发出函数的能力,这些函数通过继承基类被日志实例获取。 如果所提供的redis实现中没有一个让您大吃一惊,那么只需继承基类并覆盖emit()方法。
在下面的例子中,我们将写一个CustomRedisHandler的例子,它覆盖了它已经存在的密钥的值。
classCustomRedisHandler(RedisBaseHandler):def__init__(self,key:str,**kwargs:Any):super().__init__(**kwargs)self.key=keydefemit(self,message:logging.LogRecord):self.redis_client.set(self.key,str(message))