如何在Python中将日志写入字节流或内存流?

How to write a log to a byte or memory stream in Python?

我想将 运行 日志写入某种内存或字节流。例如,在 C# 或 Java 中,存在一个 memorystream 对象来完成此操作。有什么方法可以方便地在 Python 中将日志写入内存?

而不是这个:

file_handle = open("log.txt", "w")
# ...
if (some_error):
    file_handle.write("event 1:...")
    file_handle.write("event 2:...")
    # ...
file_handle.close()

我想将 运行 日志写入内存中的某个结构。 Python 中对此的最佳做法是什么?字符串对象?还有别的吗?

谢谢。

如果您正在寻找某种具有类似文件界面的字符串,那么您需要的是 StringIO

看起来 the StreamHandler class 最符合您的要求。

"The StreamHandler class, located in the core logging package, sends logging output to streams such as sys.stdout, sys.stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods)."

并且this HOWTO详细描述了登录python。