Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging done/fail messages

Tags:

python

logging

When using Python logging library, standard approach is just to write some message like this:

logging.info("All right")

But sometimes it necessary to show result status of some (long) task (after a while after output of main part of the message). For example:

Some long computing...    [done]

or

Some long computing...    [fail]

How can I solve this problem?

TOTAL:

Ok. It is possible, but only in the next line. For output success message in the same line you must use other tool (probably, custom), not logging Python library.

like image 250
user1051870 Avatar asked Mar 24 '26 08:03

user1051870


1 Answers

It sounds like this might help you out.

import logging

logging.basicConfig(format = "%(asctime)s - %(levelname)s - %(message)s", 
                    level = logging.DEBUG)

logging.info("Long Task is starting")
try:
    StartLongTaskFunction()
    logging.info("Long task finished")
except:
    logging.exception("Long task failed")

Note that logging.exception() is slightly different from logging.error(). After the log entry is added for logging.exception(), the entire Python error message is included as well.

If you want to log critical events in StartLongTaskFunction, you can insert log entries inside this function as well. Even if you import this function from a separate module, you can still reference the same log file.

like image 177
Michael David Watson Avatar answered Mar 25 '26 20:03

Michael David Watson



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!