Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two logging messages recorded as a single line

Tags:

python

logging

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")
like image 991
cyphics Avatar asked Dec 10 '25 11:12

cyphics


1 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.

like image 94
Vinay Sajip Avatar answered Dec 13 '25 20:12

Vinay Sajip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!