Java Code Examples for org.slf4j.MDC#get()

The following examples show how to use org.slf4j.MDC#get() . 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: GatewayInstance.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public synchronized void unRegisterEndpointInstance(String destination) {
    String oldMDC = MDC.get(Constants.MDC_TASKID);
    try {
        MDC.put(Constants.MDC_TASKID, gwCanal.getName());

        logger.info("unregister an endpoint instance with name {} begin.", destination);
        if (endpointInstances.containsKey(destination)) {
            endpointInstances.remove(destination);
            unRegisterInternal(destination);
            refreshAlarmHandler();
        } else {
            logger.info("no need to execute unregister,because this instance has been kicked out in other time.");
        }
        logger.info("unregister an endpoint instance with name {} end.", destination);
    } finally {
        if (StringUtils.isNotBlank(oldMDC)) {
            MDC.put(Constants.MDC_TASKID, oldMDC);
        } else {
            MDC.remove(Constants.MDC_TASKID);
        }
    }
}
 
Example 2
Source File: ProblemUtil.java    From loc-framework with MIT License 5 votes vote down vote up
static Problem createProblem(String detail, int code) {
  String traceId = MDC.get("traceId");
  if (traceId != null) {
    return Problem.builder().withDetail(detail).with("code", code).with("traceId", traceId)
        .withStatus(Status.OK).build();
  } else {
    return Problem.builder().withDetail(detail).with("code", code).withStatus(Status.OK).build();
  }
}
 
Example 3
Source File: UseridFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
    if (MDC.get("userid") == null) {
        MDC.put("userid", System.getProperty("user.name"));
    }

    return FilterReply.NEUTRAL;
}
 
Example 4
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  List<SafeCallable<T>> wrappedTasks = new ArrayList<>(tasks.size());
  for (Callable<T> task : tasks) {
    wrappedTasks.add(new SafeCallable<T>(user, entity, task, true));
  }
  return super.invokeAny(wrappedTasks);
}
 
Example 5
Source File: AgentManagerImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private static void tagCommand(final Command cmd) {
    final AsyncJobExecutionContext context = AsyncJobExecutionContext.getCurrent();
    if (context != null && context.getJob() != null) {
        final AsyncJob job = context.getJob();

        if (job.getRelated() != null && !job.getRelated().isEmpty()) {
            cmd.setContextParam("job", "job-" + job.getRelated() + "/" + "job-" + job.getId());
        } else {
            cmd.setContextParam("job", "job-" + job.getId());
        }
    }
    if (MDC.get("logcontextid") != null && !MDC.get("logcontextid").isEmpty()) {
        cmd.setContextParam("logid", MDC.get("logcontextid"));
    }
}
 
Example 6
Source File: NexusLogFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public FilterReply decide(final ILoggingEvent event) {
  String marker = MDC.get(MDC_MARKER_ID);

  if (MDC.get(TASK_LOG_WITH_PROGRESS_MDC) != null && INTERNAL_PROGRESS.getName().equals(marker)) {
    // internal progress logs for TaskLogType.TASK_LOG_WITH_PROGRESS are wanted
    return NEUTRAL;
  }

  if (DENY_MARKERS.stream().anyMatch(m -> m.getName().equals(marker)) || MDC.get(TASK_LOG_ONLY_MDC) != null) {
    return DENY;
  }

  return NEUTRAL;
}
 
Example 7
Source File: TracerTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "null",
    "",
    "TRACE_ID",
    "TRACE_ID,SPAN_ID,PARENT_SPAN_ID,FULL_SPAN_JSON"
}, splitBy = "\\|")
@Test
public void configureMDC_should_set_span_values_on_MDC_based_on_spanFieldsForLoggerMdc(
    String rawSpanFields
) {
    // given
    Span span = Span.newBuilder("test-span", SpanPurpose.LOCAL_ONLY)
                    .withParentSpanId("3")
                    .withTag("fooTag", "fooTagValue")
                    .withTimestampedAnnotation(Span.TimestampedAnnotation.forCurrentTime("fooEvent"))
                    .build();

    Set<SpanFieldForLoggerMdc> spanFieldsForMdc = parseRawSpanFieldsForMdc(rawSpanFields);
    Tracer.getInstance().setSpanFieldsForLoggerMdc(spanFieldsForMdc);

    // when
    Tracer.getInstance().configureMDC(span);

    // then
    for (SpanFieldForLoggerMdc fieldForMdc : SpanFieldForLoggerMdc.values()) {
        String actualMdcValue = MDC.get(fieldForMdc.mdcKey);
        if (spanFieldsForMdc != null && spanFieldsForMdc.contains(fieldForMdc)) {
            assertThat(actualMdcValue).isEqualTo(fieldForMdc.getMdcValueForSpan(span));
        }
        else {
            assertThat(actualMdcValue).isNull();
        }
    }
}
 
Example 8
Source File: HttpFSExceptionProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the HTTP status code and exception in HttpFSServer's log.
 *
 * @param status HTTP status code.
 * @param throwable exception thrown.
 */
@Override
protected void log(Response.Status status, Throwable throwable) {
  String method = MDC.get("method");
  String path = MDC.get("path");
  String message = getOneLineMessage(throwable);
  AUDIT_LOG.warn("FAILED [{}:{}] response [{}] {}", new Object[]{method, path, status, message});
  LOG.warn("[{}:{}] response [{}] {}", new Object[]{method, path, status, message}, throwable);
}
 
Example 9
Source File: MDCSpanExtensionTest.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan currentSpan = sofaTraceContext.getCurrentSpan();
    Assert.assertTrue(currentSpan != mockSpan);
    String traceIdMdc = MDC.get(MDCKeyConstants.MDC_TRACEID);
    Assert.assertTrue(traceId.equals(traceIdMdc));
}
 
Example 10
Source File: LoggingWorker.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void enqueueImplementation(final String message, String token, final long timeSpent, boolean ShowValue, String... tags) {
    final String passedToken;
    if (token == null) {
        passedToken = MDC.get(ProfiledMeasure.MDC_UUID_TOKEN_KEY);
    } else {
        passedToken = token;
    }
    measuresQueue.add(new ProfiledMeasure(message, timeSpent, ShowValue, tags, passedToken));
}
 
Example 11
Source File: ContextServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public ContextHolder getContext() {
    ContextHolder holder = new ContextHolder();
    holder.guildId = guildHolder.get();
    holder.locale = localeHolder.get();
    holder.color = colorHolder.get();
    holder.userId = MDC.get(MDC_USER);
    return holder;
}
 
Example 12
Source File: UsageLog.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static long calculateElapsedTime() {
  long endTime = System.currentTimeMillis();
  String startTimeS = MDC.get("startTime");
  if (startTimeS == null)
    return -1;
  long startTime = Long.parseLong(startTimeS);
  return endTime - startTime;
}
 
Example 13
Source File: AuditEvent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Event based on an HttpServletRequest, typically used during authentication. 
 * Solr will fill in details such as ip, http method etc from the request, and
 * username if Principal exists on the request.
 * @param eventType a predefined or custom EventType
 * @param httpRequest the request to initialize from
 */
public AuditEvent(EventType eventType, Throwable exception, HttpServletRequest httpRequest) {
  this(eventType);
  this.solrHost = httpRequest.getLocalName();
  this.solrPort = httpRequest.getLocalPort();
  this.solrIp = httpRequest.getLocalAddr();
  this.clientIp = httpRequest.getRemoteAddr();
  this.httpMethod = httpRequest.getMethod();
  this.httpQueryString = httpRequest.getQueryString();
  this.headers = getHeadersFromRequest(httpRequest);
  this.baseUrl = httpRequest.getRequestURL().toString();
  this.nodeName = MDC.get(ZkStateReader.NODE_NAME_PROP);
  SolrRequestParsers.parseQueryString(httpQueryString).forEach(sp -> {
    this.solrParams.put(sp.getKey(), Arrays.asList(sp.getValue()));
  });

  setResource(ServletUtils.getPathAfterContext(httpRequest));
  setRequestType(findRequestType());

  if (exception != null) setException(exception);

  Principal principal = httpRequest.getUserPrincipal();
  if (principal != null) {
    this.username = httpRequest.getUserPrincipal().getName();
  } else if (eventType.equals(EventType.AUTHENTICATED)) {
    this.eventType = ANONYMOUS;
    this.message = ANONYMOUS.message;
    this.level = ANONYMOUS.level;
    log.debug("Audit event type changed from AUTHENTICATED to ANONYMOUS since no Principal found on request");
  }
}
 
Example 14
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public void submitAndForget(final Runnable runnable) {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  super.submit(new SafeRunnable(user, entity, runnable, false));
}
 
Example 15
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Future<T> submit(Callable<T> task) {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  return super.submit(new SafeCallable<>(user, entity, task, true));
}
 
Example 16
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  return super.scheduleAtFixedRate(new SafeRunnable(user, entity, command, true), initialDelay, period, unit);
}
 
Example 17
Source File: NewlLineMessageConverter.java    From ns4_frame with Apache License 2.0 4 votes vote down vote up
private void logContentStart(StringBuilder stringBuilder, String logKey, String prefix,
		String tail) {
	String appendString = MDC.get(logKey); 
	stringBuilder.append(prefix).append((appendString == null ? "" : appendString)).append(tail);
}
 
Example 18
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public void scheduleWithFixedDelayAndForget(Runnable command, long initialDelay, long period, TimeUnit unit) {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  super.scheduleWithFixedDelay(new SafeRunnable(user, entity, command, false), initialDelay, period, unit);
}
 
Example 19
Source File: SafeScheduledExecutorService.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public Future<?> submit(final Runnable runnable) {
  String user = MDC.get(LogConstants.USER);
  String entity = MDC.get(LogConstants.ENTITY);
  return super.submit(new SafeRunnable(user, entity, runnable, true));
}
 
Example 20
Source File: MDCUtils.java    From spring-boot-doma2-sample with Apache License 2.0 2 votes vote down vote up
/**
 * 未設定の場合のみMDCの値を設定します。
 * 
 * @param key
 * @param value
 */
public static void putIfAbsent(String key, String value) {
    if (MDC.get(key) == null)
        MDC.put(key, value);
}