[SOLVED] Manually logging inside python functions and returning a list of all log messages


I am trying to do some detailed logging inside functions and adding every logging message inside a list object. I’m using a class to create logger objects.

from log_class import MyLog

def function1(...):

  my_logger = MyLog("Function1")

    result = ..do something
    my_logger.info("something was done ok")
    my_logger.error("something went wrong")

  log_contents = my_logger.log_capture_string.getvalue()

  return result1, log_list

def function2:(...)
  ...similar pattern

  return result2, log_list

#getting log content from both functions
for log_item in log_list:

If there is no error I can get the log list without an issue, but if there is an error and an exception is called I will not get my log_list with the my custom error message written, since nothing will be return.

Can you come up with any idea to fix this or suggest a similar approach for getting that log_list object with error messages written to it inside functions. The idea is that I want to keep adding to the log_list object again in other functions.


If you want these two lines to execute whether an error occurs or not just create a finally clause.

  log_contents = my_logger.log_capture_string.getvalue()


Answered By – Amos Baker

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *