@@ -199,6 +199,32 @@ def _readable_span(self) -> ReadableSpan:
199199 # kind=self.kind,
200200 )
201201
202+ def _should_collect_stack (self , level : str , is_errored : bool ) -> bool :
203+ """Determine if stack trace should be collected based on level and error state."""
204+ if level == "all" :
205+ return True
206+ if level == "error" and is_errored :
207+ return True
208+ return False
209+
210+ def _should_exclude_frame (self , frame ) -> bool :
211+ """Check if a frame should be excluded from the stack trace."""
212+ if "INSTANA_DEBUG" in os .environ :
213+ return False
214+ if _re_tracer_frame .search (frame [0 ]):
215+ return True
216+ if _re_with_stan_frame .search (frame [2 ]):
217+ return True
218+ return False
219+
220+ def _apply_stack_limit (self , sanitized_stack : list , limit : int , use_full_stack : bool ) -> list :
221+ """Apply frame limit to the sanitized stack."""
222+ if use_full_stack or len (sanitized_stack ) <= limit :
223+ return sanitized_stack
224+ # (limit * -1) gives us negative form of <limit> used for
225+ # slicing from the end of the list. e.g. stack[-25:]
226+ return sanitized_stack [(limit * - 1 ) :]
227+
202228 def _add_stack (self , is_errored : bool = False ) -> None :
203229 """
204230 Adds a backtrace to <span> based on configuration.
@@ -210,16 +236,7 @@ def _add_stack(self, is_errored: bool = False) -> None:
210236 limit = options .stack_trace_length
211237
212238 # Determine if we should collect stack trace
213- should_collect = False
214-
215- if level == "all" :
216- should_collect = True
217- elif level == "error" and is_errored :
218- should_collect = True
219- elif level == "none" :
220- should_collect = False
221-
222- if not should_collect :
239+ if not self ._should_collect_stack (level , is_errored ):
223240 return
224241
225242 # For erroneous EXIT spans, MAY consider the whole stack
@@ -234,22 +251,12 @@ def _add_stack(self, is_errored: bool = False) -> None:
234251 trace_back .reverse ()
235252
236253 for frame in trace_back :
237- # Exclude Instana frames unless we're in dev mode
238- if "INSTANA_DEBUG" not in os .environ :
239- if _re_tracer_frame .search (frame [0 ]):
240- continue
241- if _re_with_stan_frame .search (frame [2 ]):
242- continue
243-
254+ if self ._should_exclude_frame (frame ):
255+ continue
244256 sanitized_stack .append ({"c" : frame [0 ], "n" : frame [1 ], "m" : frame [2 ]})
245257
246258 # Apply limit (unless it's an errored span and we want full stack)
247- if not use_full_stack and len (sanitized_stack ) > limit :
248- # (limit * -1) gives us negative form of <limit> used for
249- # slicing from the end of the list. e.g. stack[-25:]
250- self .stack = sanitized_stack [(limit * - 1 ) :]
251- else :
252- self .stack = sanitized_stack
259+ self .stack = self ._apply_stack_limit (sanitized_stack , limit , use_full_stack )
253260
254261 except Exception :
255262 logger .debug ("span._add_stack: " , exc_info = True )
0 commit comments