Home > front end >  Manually logging inside python functions and returning a list of all log messages
Manually logging inside python functions and returning a list of all log messages

Time:03-22

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")

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

  log_contents = my_logger.log_capture_string.getvalue()
  log_list.append(log_contents)

  return result1, log_list

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

  return result2, log_list

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

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.

CodePudding user response:

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

finally:
  log_contents = my_logger.log_capture_string.getvalue()
  log_list.append(log_contents)

https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

  • Related