如何在Python日志记录模块中禁止换行. [英] How can I suppress newline in Python logging module.
问题描述
例如,我想取消换行符log.info("msg"). 当我们打印"它时
I would like to cancel newline when I do for example log.info("msg"). When we do "print" it just
print msg,
所以我需要像昏迷一样的日志记录.
So I need something like coma for logging.
我播这个问题 在Python日志记录模块中禁止换行符 但任何人都可以给我参考或举个简单的例子,例如"Hello world" 谢谢!
I sow this question Suppress newline in Python logging module but can anybody give me reference or a simple example like "Hello world" Thanks!
推荐答案
以下是我对类似问题的回答:
将新行\n
插入StreamHandler
类的emit(...)
方法内部.
The new line, \n
, is inserted inside the StreamHandler
class's emit(...)
method.
如果您确实对修复这一行为感兴趣,那么以下是我如何通过猴子补丁 logging.StreamHandler类内部的emit(self, record)
方法.
If you're really set on fixing this behaviour, then here's an example of how I solved this by monkey patching the emit(self, record)
method inside the logging.StreamHandler class.
猴子补丁是一种在不更改原始源代码的情况下扩展或修改动态语言的运行时代码的方法.此过程也被称为鸭打孔.
A monkey patch is a way to extend or modify the run-time code of dynamic languages without altering the original source code. This process has also been termed duck punching.
这是emit()
的自定义实现,省略了换行符:
Here is the custom implementation of emit()
that omits line breaks:
def customEmit(self, record):
# Monkey patch Emit function to avoid new lines between records
try:
msg = self.format(record)
if not hasattr(types, "UnicodeType"): #if no unicode support...
self.stream.write(msg)
else:
try:
if getattr(self.stream, 'encoding', None) is not None:
self.stream.write(msg.encode(self.stream.encoding))
else:
self.stream.write(msg)
except UnicodeError:
self.stream.write(msg.encode("UTF-8"))
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
然后,您将创建一个自定义的日志记录类(在这种情况下,是TimedRotatingFileHandler
的子类).
Then you would make a custom logging class (in this case, subclassing from TimedRotatingFileHandler
).
class SniffLogHandler(TimedRotatingFileHandler):
def __init__(self, filename, when, interval, backupCount=0,
encoding=None, delay=0, utc=0):
# Monkey patch 'emit' method
setattr(StreamHandler, StreamHandler.emit.__name__, customEmit)
TimedRotatingFileHandler.__init__(self, filename, when, interval,
backupCount, encoding, delay, utc)
有人可能会认为这种解决方案不是 Pythonic 或类似的东西.可能是这样,所以要小心.
Some people might argue that this type of solution is not Pythonic, or whatever. It might be so, so be careful.
另外,请注意,这将全局修补SteamHandler.emit(...)
,因此,如果您正在使用多个日志记录类,则此修补程序也会影响其他日志记录类!
Also, be aware that this will globally patch SteamHandler.emit(...)
, so if you are using multiple logging classes, then this patch will affect the other logging classes as well!
希望有帮助.
这篇关于如何在Python日志记录模块中禁止换行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!