python - Streaming from Python logging/stdout to a redis connection
问题描述
How can I stream Python stdout (or logging) to a redis connection?
There is a long running job that I need to capture logs for in realtime. It's not feasible to wait until the job is finished to get the logs, in case of failure there needs to be record of what happened.
I have managed to capture logging output to stdout in a StringIO buffer that can be read when the long running job is finished.
What I can't figure out is how to get that buffer to interact with the redis client in realtime, while the job is still running.
解决方案
我想到了:
from io import StringIO
class RedisHandler(StringIO):
def __init__(self, key, redis_client):
"""
Create a new StringIO interface for the given key and redis_client.
"""
StringIO.__init__(self)
self.key = key
self.redis_client = redis_client
def write(self, record):
"""
Publish record to redis logging list
"""
self.redis_client.lpush(self.key, record)
在主脚本中,我将 stdout + stderr 重定向到 RedisHandler 实例。Redis 充当 StringIO 的端点,并将日志输出中的每一行添加到列表中。
推荐阅读
- android - 使用 Android 信标库查找设备到 Eddystone 信标的距离
- ios - ionic cordova 语音识别插件在 android 上运行良好,但在 ios 上失败
- google-cloud-platform - howto:超时后重新启动守护程序服务?
- python - 哪个是最简单(最快且可能不安全)的可逆固定大小保长对称密码学?
- ios - compactMapValues 不过滤 nil 值
- rust - 结构中的 Rust 生命周期范围
- azure-devops - 组织之间的 Azure DevOps Repos 同步
- c - 如何使用android内核源代码在文件中运行写东西?
- c++ - 在 C++ 中的任何给定时间只运行给定数量的线程
- python-3.x - 使用 os.path 和 pathlib Mac OSX Catalina 时的奇怪路径行为