11

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!

Community
  • 1
  • 1
Maxim13
  • 121
  • 1
  • 1
  • 4
  • 1
    So you want to concatenate multiple log entries? The problem is that log entries are like separate pieces of paper. While print keeps writing on the same sheet, log actually always starts with a fresh new one. – Jure C. Oct 02 '12 at 23:01
  • 2
    I've found solution here http://stackoverflow.com/questions/3118059/how-to-write-custom-python-logging-handler?answertab=active#tab-top It works for me. – Maxim13 Oct 03 '12 at 17:25
  • In Python >= 3.2, one can use [`StreamHandler.terminate = ''`](https://docs.python.org/3/library/logging.handlers.html#streamhandler). – Ninjakannon Apr 24 '16 at 12:27

2 Answers2

7

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.

Community
  • 1
  • 1
pjama
  • 3,014
  • 3
  • 26
  • 27
5

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.

Hans Then
  • 10,935
  • 3
  • 32
  • 51