@@ -69,3 +69,48 @@ Within those logs, you should be able to see the culprit:
6969test_app- 1 | File " /src/test_app/views.py" , line 185 , in timeout_view
7070test_app- 1 | time.sleep(60 * 10 ) # 10 minutes
7171```
72+
73+ # # Method Runtime Helper
74+
75+ As a general utility, sometimes you want to log if a particular method takes longer than a certain time.
76+ This is true in almost any case where a method is doing something known to be performance- sensitive,
77+ such as processing Ansible facts in AWX .
78+
79+ ```python
80+ import logging
81+
82+ logger = logging.getLogger(' my_app.tasks.cleanup' )
83+
84+ @ log_excess_runtime(logger, cutoff = 2.0 )
85+ def cleanup(self ):
86+ # Do stuff that could take a long time
87+ ```
88+
89+ Then if the `cleaup` method takes over 2.0 seconds, you should see a log like this:
90+
91+ ```
92+ DEBUG dab_runtime_logger:runtime.py:42 Running ' cleanup' took 2. 30s
93+ ```
94+
95+ Because you are passing in your own logger, you can control everything about how those logs are handed.
96+ If you need to customize the thresholds or log message, you can pass kwards to
97+ the `@ log_excess_runtime` call.
98+ - `cutoff` - time cutoff, any time greater than this causes an INFO level log
99+ - `debug_cutoff` - any time greater than this causes a DEBUG level log
100+ - `msg` - the log message with format strings in it
101+ - `add_log_data` - add a kwarg `log_data` to the method call as a dict that the method can attach additional log data to
102+
103+ The `msg` and `add_log_data` are intended to interact.
104+ For an example, imagine that the `cleanup` method deletes files an keeps a count, `deleted_count` .
105+ The number of deleted fields could be added to the log message with this.
106+
107+ ```python
108+ import logging
109+
110+ logger = logging.getLogger(' my_app.tasks.cleanup' )
111+
112+ @ log_excess_runtime(logger, cutoff = 2.0 , msg = ' Cleanup took {delta:.2f } s, deleted {files_deleted} ' )
113+ def cleanup(self , log_data):
114+ # Do stuff that could take a long time
115+ log_data[' files_deleted' ] = deleted_count
116+ ```
0 commit comments