Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress newline in Python logging module

Tags:

python

logging

I'm trying to replace an ad-hoc logging system with Python's logging module. I'm using the logging system to output progress information for a long task on a single line so you can tail the log or watch it in a console. I've done this by having a flag on my logging function which suppresses the newline for that log message and build the line piece by piece.

All the logging is done from a single thread so there's no serialisation issues.

Is it possible to do this with Python's logging module? Is it a good idea?

like image 814
Peter Graham Avatar asked Aug 23 '11 23:08

Peter Graham


People also ask

What does logging module do in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.

What is propagate in Python logging?

Propagate: Decides whether a log should be propagated to the logger's parent. By default, its value is True. A level: Like the log handler level, the logger level is used to filter out “less important” logs.

Is logging blocking in Python?

Sometimes you have to get your logging handlers to do their work without blocking the thread you're logging from. This is common in Web applications, though of course it also occurs in other scenarios. So, although not explicitly mentioned yet logging does seem to be blocking. For details see Python Docs.


2 Answers

If you wanted to do this you can change the logging handler terminator. I'm using Python 3.4. This was introduced in Python 3.2 as stated by Ninjakannon.

handler = logging.StreamHandler() handler.terminator = "" 

When the StreamHandler writes it writes the terminator last.

like image 177
justengel Avatar answered Sep 17 '22 03:09

justengel


Let's start with your last question: No, I do not believe it's a good idea. IMO, it hurts the readability of the logfile in the long run.

I suggest sticking with the logging module and using the '-f' option on your 'tail' command to watch the output from the console. You will probably end up using the FileHandler. Notice that the default argument for 'delay' is False meaning the output won't be buffered.

If you really needed to suppress newlines, I would recommend creating your own Handler.

like image 29
jonEbird Avatar answered Sep 18 '22 03:09

jonEbird