Created
April 23, 2021 16:59
-
-
Save bryantcj52/8e5cce3d1a98d3da89b089bcf230ba61 to your computer and use it in GitHub Desktop.
APM Sling MDC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import co.elastic.apm.api.ElasticApm; | |
import org.apache.felix.scr.annotations.sling.SlingFilter; | |
import org.apache.felix.scr.annotations.sling.SlingFilterScope; | |
import org.apache.sling.api.SlingHttpServletRequest; | |
import org.slf4j.MDC; | |
import javax.servlet.*; | |
import java.io.IOException; | |
/** | |
* The SlingFilterScope.REQUEST is important as MDC needs to be configured prior | |
* to any logger being executed in the page rendering. | |
*/ | |
@SlingFilter( | |
label = "APM MDC Filter", | |
description = "Elastic APM MDC filter to get IDs", | |
order = 0, | |
scope = {SlingFilterScope.REQUEST}) | |
public class MDCLoggerFilter implements javax.servlet.Filter{ | |
public static final String TRACE_ID = "trace.id"; | |
public static final String TRANSACTION_ID = "transaction.id"; | |
public static final String SPAN_ID = "span.id"; | |
private static final String[] MDC_CUSTOM_KEYS = { | |
TRACE_ID, | |
TRANSACTION_ID, | |
SPAN_ID, | |
}; | |
public void init(FilterConfig filterConfig) throws ServletException { | |
} | |
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, | |
FilterChain filterChain) throws IOException, ServletException { | |
final SlingHttpServletRequest request = (SlingHttpServletRequest) servletRequest; | |
try { | |
insertIntoMDC(request); | |
filterChain.doFilter(request, servletResponse); | |
} finally { | |
clearMDC(); | |
} | |
} | |
private void clearMDC() { | |
for (String key : MDC_CUSTOM_KEYS) { | |
MDC.remove(key); | |
} | |
} | |
private void insertIntoMDC(SlingHttpServletRequest request) { | |
//logic can go here to take value from request object. | |
// Can also utilize ResourceResolver from same request. | |
// If needed, can also write a generic OSGi Configuration | |
// (String Array Properties) to read from standard request objects, | |
// i.e cookies, headers, and parameters. | |
MDC.put(TRACE_ID, ElasticApm.currentTransaction().getTraceId()); | |
MDC.put(TRANSACTION_ID, ElasticApm.currentTransaction().getId()); | |
MDC.put(SPAN_ID, ElasticApm.currentSpan().getId()); | |
} | |
public void destroy() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment