10
10
11
11
from helpers import constants
12
12
from helpers .handler import FormattedMessageCollectorHandler
13
+ from helpers .imports import undo_imports_from_package
13
14
14
15
LOGGER_NAME = "flask-test"
15
16
@@ -29,7 +30,7 @@ def client_and_log_handler():
29
30
30
31
# Add json_logging
31
32
json_logging .init_flask (enable_json = True )
32
- json_logging .init_request_instrument (app )
33
+ json_logging .init_request_instrument (app , exclude_url_patterns = [ "/no-request-instrumentation" ] )
33
34
34
35
# Prepare test endpoints
35
36
@app .route ("/log/levels/debug" )
@@ -67,12 +68,16 @@ def log_exception():
67
68
def get_correlation_id ():
68
69
return {'correlation_id' : json_logging .get_correlation_id ()}
69
70
71
+ @app .route ('/no-request-instrumentation' )
72
+ def excluded_from_request_instrumentation ():
73
+ return {}
74
+
70
75
with app .test_client () as test_client :
71
76
yield test_client , handler
72
77
73
78
# Tear down test environment
74
79
logger .removeHandler (handler )
75
- del sys . modules [ "json_logging" ] # "de-import" because json_logging maintains global state
80
+ undo_imports_from_package ( "json_logging" ) # Necessary because of json-logging's global state
76
81
77
82
78
83
@pytest .mark .parametrize ("level" , ["debug" , "info" , "error" ])
@@ -162,3 +167,26 @@ def test_exception_logged_with_stack_trace(client_and_log_handler):
162
167
assert "Traceback (most recent call last):" in msg ["exc_info" ], "Not a stack trace"
163
168
assert "RuntimeError" in msg ["exc_info" ], "Exception type not logged"
164
169
assert len (msg ["exc_info" ].split ("\n " )) > 2 , "Stacktrace doesn't have multiple lines"
170
+
171
+
172
+ def test_request_instrumentation (client_and_log_handler ):
173
+ api_client , _ = client_and_log_handler
174
+ request_logger = logging .getLogger ("flask-request-logger" )
175
+ handler = FormattedMessageCollectorHandler ()
176
+ request_logger .addHandler (handler )
177
+
178
+ response = api_client .get ("/log/levels/debug" )
179
+
180
+ assert response .status_code == 200
181
+ assert len (handler .messages ) == 1
182
+
183
+ def test_excluded_from_request_instrumentation (client_and_log_handler ):
184
+ api_client , _ = client_and_log_handler
185
+ request_logger = logging .getLogger ("flask-request-logger" )
186
+ handler = FormattedMessageCollectorHandler ()
187
+ request_logger .addHandler (handler )
188
+
189
+ response = api_client .get ("/no-request-instrumentation" )
190
+
191
+ assert response .status_code == 200
192
+ assert len (handler .messages ) == 0
0 commit comments