@@ -123,34 +123,43 @@ def record_exception(exc: Exception, span_name: Optional[str] = None) -> None:
123
123
def extract_function_code (tb_frame , lineno ):
124
124
"""Extracts the full function body where the exception occurred."""
125
125
try :
126
+ # Get the source lines and the starting line number of the function
126
127
source_lines , start_line = inspect .getsourcelines (tb_frame )
127
128
end_line = start_line + len (source_lines ) - 1
128
129
130
+ # If the function body is too long, limit the number of lines
129
131
if len (source_lines ) > 20 :
130
- # Get 10 lines above and 10 below the exception line
131
- start_idx = max (0 , lineno - start_line - 10 )
132
- end_idx = min (len (source_lines ), lineno - start_line + 10 )
133
- source_lines = source_lines [(start_idx - 1 ):end_idx ]
134
-
135
- start_line = start_line + start_idx
136
- end_line = start_line + end_idx
137
-
138
- function_code = "" .join (source_lines ) # Convert to a string
139
-
132
+ # Define the number of lines to show before and after the exception line
133
+ lines_before = 10
134
+ lines_after = 10
135
+
136
+ # Calculate the start and end indices for slicing
137
+ start_idx = max (0 , lineno - start_line - lines_before )
138
+ end_idx = min (len (source_lines ), lineno - start_line + lines_after )
139
+
140
+ # Extract the relevant lines
141
+ source_lines = source_lines [start_idx :end_idx ]
142
+
143
+ # Adjust the start and end line numbers
144
+ start_line += start_idx
145
+ end_line = start_line + len (source_lines ) - 1
146
+
147
+ # Convert the list of lines to a single string
148
+ function_code = "" .join (source_lines )
149
+
140
150
return {
141
151
"function_code" : function_code ,
142
152
"function_start_line" : start_line ,
143
153
"function_end_line" : end_line ,
144
- }
145
-
154
+ }
155
+
146
156
except Exception as e :
157
+ # Handle cases where the source code cannot be extracted
147
158
return {
148
159
"function_code" : f"Error extracting function code: { e } " ,
149
160
"function_start_line" : None ,
150
- "function_end_line" : None
161
+ "function_end_line" : None ,
151
162
}
152
-
153
- _original_record_exception = Span .record_exception
154
163
155
164
def custom_record_exception_wrapper (self : Span ,
156
165
exception : BaseException ,
0 commit comments