org.jboss.logging.MDC Java Examples

The following examples show how to use org.jboss.logging.MDC. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MDCScope.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public void close() {
    wrapped.close();
    MDC.remove(TRACE_ID);
    MDC.remove(SPAN_ID);
    MDC.remove(SAMPLED);

    if (originalTraceId != null) {
        MDC.put(TRACE_ID, originalTraceId);
    }
    if (originalSpanId != null) {
        MDC.put(SPAN_ID, originalSpanId);
    }
    if (originalSampled != null) {
        MDC.put(SAMPLED, originalSampled);
    }
}
 
Example #2
Source File: Demo.java    From hystrix-context-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPropagateMdcContext() {

    // given
    MDC.put(REQUEST_ID, requestId);

    // when
    final Object result = new HystrixCommand<Object>(commandGroup(GROUP_KEY)) {
        @Override
        protected Object run() throws Exception {
            return MDC.get(REQUEST_ID);
        }
    }.execute();

    // then
    assertEquals(requestId, result);
}
 
Example #3
Source File: NestedMdcScopesTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void mdcIsRestoredCorrectly() {
    ThreadLocalScopeManager threadLocalScopeManager = new ThreadLocalScopeManager();
    MDCScopeManager mdcScopeManager = new MDCScopeManager(threadLocalScopeManager);

    assertNull(mdcScopeManager.active());
    assertNull(threadLocalScopeManager.active());
    assertNull(MDC.get("traceId"));

    JaegerSpanContext span = new JaegerSpanContext(1, 1, 1, 1, Byte.valueOf("0"));
    Scope scope = mdcScopeManager.activate(new TestSpan(span), true);
    assertSame(span, threadLocalScopeManager.active().span().context());
    assertEquals("10000000000000001", MDC.get("traceId"));

    JaegerSpanContext subSpan = new JaegerSpanContext(2, 2, 2, 1, Byte.valueOf("0"));
    Scope subScope = mdcScopeManager.activate(new TestSpan(subSpan), true);
    assertSame(subSpan, threadLocalScopeManager.active().span().context());
    assertEquals("20000000000000002", MDC.get("traceId"));

    subScope.close();

    assertSame(span, threadLocalScopeManager.active().span().context());
    assertEquals("10000000000000001", MDC.get("traceId"));

    scope.close();

    assertNull(mdcScopeManager.active());
    assertNull(threadLocalScopeManager.active());
    assertNull(MDC.get("traceId"));
}
 
Example #4
Source File: MDCScope.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public MDCScope(Scope scope) {
    this.wrapped = scope;
    this.originalTraceId = MDC.get(TRACE_ID);
    this.originalSpanId = MDC.get(SPAN_ID);
    this.originalSampled = MDC.get(SAMPLED);
    if (scope.span().context() instanceof JaegerSpanContext) {
        putContext((JaegerSpanContext) scope.span().context());
    }
}
 
Example #5
Source File: BaseProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
public void startRequest(HttpServletRequest theRequest) {
    if (theRequest == null) {
        return;
    }

    Set<String> headerNames = new TreeSet<String>();
    for (Enumeration<String> enums = theRequest.getHeaderNames(); enums.hasMoreElements();) {
        headerNames.add(enums.nextElement());
    }
    ourLog.debug("Request headers: {}", headerNames);

    Enumeration<String> forwardedFors = theRequest.getHeaders("x-forwarded-for");
    StringBuilder b = new StringBuilder();
    for (Enumeration<String> enums = forwardedFors; enums != null && enums.hasMoreElements();) {
        if (b.length() > 0) {
            b.append(" / ");
        }
        b.append(enums.nextElement());
    }

    String forwardedFor = b.toString();
    String ip = theRequest.getRemoteAddr();
    if (StringUtils.isBlank(forwardedFor)) {
        org.slf4j.MDC.put(REMOTE_ADDR, ip);
        ourLog.debug("Request is from address: {}", ip);
    } else {
        org.slf4j.MDC.put(REMOTE_ADDR, forwardedFor);
        ourLog.debug("Request is from forwarded address: {}", forwardedFor);
    }

    String userAgent = StringUtils.defaultString(theRequest.getHeader("user-agent"));
    org.slf4j.MDC.put(REMOTE_UA, userAgent);

}
 
Example #6
Source File: TicketFilter.java    From portal-de-servicos with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    try {
        String ticket = tickets.next().toString();

        MDC.put(TICKET_KEY, ticket);
        request.setAttribute(TICKET_KEY, ticket);

        chain.doFilter(request, response);
    } finally {
        MDC.remove(TICKET_KEY);
    }
}
 
Example #7
Source File: Main.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The main method.
 *
 * @param args the command-line arguments
 */
public static void main(String[] args) throws IOException {
    MDC.put("process", "host controller");


    // Grab copies of our streams.
    final InputStream in = System.in;
    //final PrintStream out = System.out;
    //final PrintStream err = System.err;

    byte[] authKey = new byte[ProcessController.AUTH_BYTES_ENCODED_LENGTH];
    try {
        StreamUtils.readFully(new Base64InputStream(System.in), authKey);
    } catch (IOException e) {
        STDERR.println(HostControllerLogger.ROOT_LOGGER.failedToReadAuthenticationKey(e));
        fail();
        return;
    }

    // Make sure our original stdio is properly captured.
    try {
        Class.forName(ConsoleHandler.class.getName(), true, ConsoleHandler.class.getClassLoader());
    } catch (Throwable ignored) {
    }

    // Install JBoss Stdio to avoid any nasty crosstalk.
    StdioContext.install();
    final StdioContext context = StdioContext.create(
        new NullInputStream(),
        new LoggingOutputStream(Logger.getLogger("stdout"), Level.INFO),
        new LoggingOutputStream(Logger.getLogger("stderr"), Level.ERROR)
    );
    StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context));

    create(args, new String(authKey, Charset.forName("US-ASCII")));

    while (in.read() != -1) {}
    exit();
}
 
Example #8
Source File: MDCScope.java    From quarkus with Apache License 2.0 4 votes vote down vote up
protected void putContext(JaegerSpanContext spanContext) {
    MDC.put(TRACE_ID, spanContext.getTraceId());
    MDC.put(SPAN_ID, String.format("%16x", spanContext.getSpanId()));
    MDC.put(SAMPLED, Boolean.toString(spanContext.isSampled()));
}
 
Example #9
Source File: AbstractLoadPlanBuildingAssociationVisitationStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void finish() {
	propertyPathStack.pop();
	MDC.remove( MDC_KEY );
	fetchSourceStack.clear();
}
 
Example #10
Source File: AbstractLoadPlanBuildingAssociationVisitationStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void push(PropertyPath path) {
	pathStack.addFirst( path );
	MDC.put( MDC_KEY, extractFullPath( path ) );
}
 
Example #11
Source File: AbstractLoadPlanBuildingAssociationVisitationStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void pop() {
	pathStack.removeFirst();
	PropertyPath newHead = pathStack.peekFirst();
	MDC.put( MDC_KEY, extractFullPath( newHead ) );
}
 
Example #12
Source File: BaseProvider.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public void endRequest(HttpServletRequest theRequest) {
    MDC.remove(REMOTE_ADDR);
    MDC.remove(REMOTE_UA);
}
 
Example #13
Source File: LoggingServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressWarnings("Convert2Lambda")
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            final Map<String, Deque<String>> params = new TreeMap<>(exchange.getQueryParameters());
            final String msg = getValue(params, MSG_KEY, DEFAULT_MESSAGE);
            final boolean includeLevel = getValue(params, INCLUDE_LEVEL_KEY, false);
            final int logCount = getValue(params, LOG_COUNT_KEY, 1);
            final boolean logInfoOnly = getValue(params, LOG_INFO_ONLY_KEY, false);
            final boolean logException = getValue(params, LOG_EXCEPTION_KEY, false);
            final String ndcValue = getValue(params, NDC_KEY, null);
            final Set<Logger.Level> logLevels = getLevels(params);
            final String loggerName = getValue(params, LOG_NAME_KEY, null);
            if (ndcValue != null) {
                NDC.push(ndcValue);
            }
            // Assume other parameters are MDC key/value pairs
            for (String key : params.keySet()) {
                MDC.put(key, params.get(key).getFirst());
            }
            final Logger logger = (loggerName == null ? LOGGER : Logger.getLogger(loggerName));
            for (int i = 0; i < logCount; i++) {
                if (logInfoOnly) {
                    logger.info(getMessage(msg, Logger.Level.INFO, includeLevel));
                } else {
                    for (Logger.Level level : logLevels) {
                        if (logException) {
                            logger.log(level, getMessage(msg, level, includeLevel), createMultiNestedCause());
                        } else {
                            logger.log(level, getMessage(msg, level, includeLevel));
                        }
                    }
                }
            }
            // Clear NDC and MDC
            NDC.clear();
            MDC.clear();
            exchange.getResponseSender().send("Response sent");
        }
    };
}