Need advice on how to separate logging functions from data processing in Python

In my project, I have a set of classes that do some work, invoking external commands and returning their results. Let me call them "reports."

I want to add an entry to these reports, however the specific log object will be determined at runtime, and not at the time the classes are defined.

So, at the moment I see two options for implementing logging:

I am. At run time, create an instance of the ReportLogger class that can secure all the data in report instances using logging functions using a specific logger.

Pros:

  • You can apply registration to any child report class that I really need, and not touch other classes.

Minuses:

  • Magic! Monkey-patching is not an explicit way to do something.
  • Logging is actually used at runtime, so it’s less clear to understand that there is some kind of logging when looking for code.

II. Singleton ReportLogger , which wraps all reports at creation time through decorators, but accepts a specific logger at run time.

Pros:

  • An explicit and clean way to note that these reports require logging (and actually apply it).

Minuses:

  • It is more difficult to deal with child classes that inherit from the Report base class. If, for example, in the base class Report , some method, for example collect_data() , is decorated with @log_collect_data , then for child classes registration will be closely related to collect_data() . Or maybe I need to split the actual code from collect_data() to, say, _collect_data() to change it in child classes, call _collect_data() from collect_data() and then wrap collect_data() with @log_collect_data .

I like the second method, but I want to deal with child classes better than _collect_data (). Any advice is appreciated!

+4
source share

Source: https://habr.com/ru/post/1442804/


All Articles