1
1
package works .weave .socks .cart .middleware ;
2
2
3
3
import io .prometheus .client .Histogram ;
4
+ import org .springframework .beans .factory .annotation .Autowired ;
4
5
import org .springframework .beans .factory .annotation .Value ;
6
+ import org .springframework .web .method .HandlerMethod ;
5
7
import org .springframework .web .servlet .HandlerInterceptor ;
6
8
import org .springframework .web .servlet .ModelAndView ;
9
+ import org .springframework .web .servlet .mvc .method .RequestMappingInfo ;
10
+ import org .springframework .web .servlet .mvc .method .annotation .RequestMappingHandlerMapping ;
7
11
8
12
import javax .servlet .http .HttpServletRequest ;
9
13
import javax .servlet .http .HttpServletResponse ;
14
+ import java .util .Map ;
10
15
11
16
public class HTTPMonitoringInterceptor implements HandlerInterceptor {
12
17
static final Histogram requestLatency = Histogram .build ()
@@ -20,6 +25,9 @@ public class HTTPMonitoringInterceptor implements HandlerInterceptor {
20
25
@ Value ("${spring.application.name:carts}" )
21
26
private String serviceName ;
22
27
28
+ @ Autowired
29
+ private RequestMappingHandlerMapping requestMappingHandlerMapping ;
30
+
23
31
@ Override
24
32
public boolean preHandle (HttpServletRequest httpServletRequest , HttpServletResponse
25
33
httpServletResponse , Object o ) throws Exception {
@@ -36,7 +44,7 @@ public void postHandle(HttpServletRequest httpServletRequest, HttpServletRespons
36
44
requestLatency .labels (
37
45
serviceName ,
38
46
httpServletRequest .getMethod (),
39
- httpServletRequest . getServletPath ( ),
47
+ getMatchingURLPattern ( httpServletRequest ),
40
48
Integer .toString (httpServletResponse .getStatus ())
41
49
).observe (seconds );
42
50
}
@@ -45,4 +53,21 @@ public void postHandle(HttpServletRequest httpServletRequest, HttpServletRespons
45
53
public void afterCompletion (HttpServletRequest httpServletRequest , HttpServletResponse
46
54
httpServletResponse , Object o , Exception e ) throws Exception {
47
55
}
56
+
57
+ private String getMatchingURLPattern (HttpServletRequest httpServletRequest ) {
58
+ String res = httpServletRequest .getServletPath ();
59
+
60
+ for (Map .Entry <RequestMappingInfo , HandlerMethod > item : requestMappingHandlerMapping
61
+ .getHandlerMethods ().entrySet ()) {
62
+ RequestMappingInfo mapping = item .getKey ();
63
+ if (mapping .getPatternsCondition ().getMatchingCondition (httpServletRequest ) != null &&
64
+ mapping .getMethodsCondition ().getMatchingCondition (httpServletRequest ) !=
65
+ null ) {
66
+ res = mapping .getPatternsCondition ().getMatchingCondition (httpServletRequest )
67
+ .getPatterns ().iterator ().next ();
68
+ break ;
69
+ }
70
+ }
71
+ return res ;
72
+ }
48
73
}
0 commit comments