How can I suppress newline in Python logging modul

2019-02-08 16:41发布

This question already has an answer here:

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.

I sow this question Suppress newline in Python logging module but can anybody give me reference or a simple example like “Hello world” Thanks!

2条回答
对你真心纯属浪费
2楼-- · 2019-02-08 17:19

This is not possible (without some serious hacking into the logging module). If you must have this functionality, build up the logging string in parts and log it ony when you are ready to display a log message with newline.

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-08 17:23

Here is what I answered for a similar question:

The new line, \n, is inserted inside the StreamHandler class's emit(...) method.

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.

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)

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)

Some people might argue that this type of solution is not Pythonic, or whatever. It might be so, so be careful.

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!

Hope that helps.

查看更多
登录 后发表回答