Two logging messages recorded as a single line

Viewed 413

I'm migrating from using print() statements everywhere in my scripts to a more serious logging system. I'm using the logging module to manage the task. There's one thing I can't seem to achieve with it though:

In some cases, I want to create a log entry in two distinct steps, but recorded on the same line. Something that would classically look like this:

Initiating procedure... OK

In this case, the OK part would be recorded only if the task is successful.

I used to achieve that with the following print commands:

print('Initiating procedure... ', end="", flush=True)
...
print('OK')

Is there a way to achieve a similar thing with the logging module? Something like

logging.info("First message", end="", flush=True)
...
logging.info("OK")
2 Answers

You could use a BufferingHandler such as a MemoryHandler together with a custom formatter to achieve what you want. This approach buffers records in memory until flushed, and the flushing writes to a target handler and allows you to potentially merge two logging records into a single output event.

I am not sure it is a good idea. I don't think that logs are meant to be used this way. You will often see before your log message informations about date, time, nature of the log message.

Do you really want a line like this :

INFO:ROOT 2018-09-01 22:12:13 Initiating procedure... INFO:ROOT 2018-09-01 22:12:17 OK

on the same line ?

Often you will parse your logs using other technologies (I often parse logs with awk) and I'm sure I would be very disturbed by that kind of logs.

Related