Python Logging Annotation – Automatically create logger for methods

This is a pattern for creating an annotation that will “inject” a logger into a python method. This allows you to decorate a python method with @logged and you will have a variable named logger created with your method name.

This is nice because you do not have to have boilerplate code all over the place.  It also allows you to easily have a logger for each function instead of a global logger.  This makes reading logs much easier since you can tell exactly where your logging call was made.

Here is an outline of the process, the comments in the code explain where these steps happen:

  1. Get the global variables for the decorated function
  2. If there is an existing logger in the function, we save it
  3. Create a new logger with the function name as the logger name
  4. Set the new logger as a global variable for the function
  5. Call the function
  6. Restore the existing logger as a global

Now your methods will look like this:

Leave a Reply

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