org.slf4j.MDC#get ( )源码实例Demo

下面列出了org.slf4j.MDC#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: DataLink   文件: GatewayInstance.java
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);
        }
    }
}
 
源代码2 项目: loc-framework   文件: ProblemUtil.java
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();
  }
}
 
源代码3 项目: lucene-solr   文件: AuditEvent.java
/**
 * 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");
  }
}
 
源代码4 项目: tds   文件: UsageLog.java
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;
}
 
源代码5 项目: JuniperBot   文件: ContextServiceImpl.java
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;
}
 
源代码6 项目: GreenSummer   文件: LoggingWorker.java
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));
}
 
源代码7 项目: sofa-tracer   文件: MDCSpanExtensionTest.java
@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));
}
 
源代码8 项目: big-c   文件: HttpFSExceptionProvider.java
/**
 * 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);
}
 
源代码9 项目: wingtips   文件: TracerTest.java
@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();
        }
    }
}
 
源代码10 项目: nexus-public   文件: NexusLogFilter.java
@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;
}
 
源代码11 项目: cosmic   文件: AgentManagerImpl.java
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"));
    }
}
 
@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);
}
 
源代码13 项目: api-layer   文件: UseridFilter.java
@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;
}
 
@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));
}
 
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);
}
 
源代码16 项目: ns4_frame   文件: NewlLineMessageConverter.java
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);
}
 
@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));
}
 
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));
}
 
@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);
}
 
源代码20 项目: spring-boot-doma2-sample   文件: MDCUtils.java
/**
 * 未設定の場合のみMDCの値を設定します。
 * 
 * @param key
 * @param value
 */
public static void putIfAbsent(String key, String value) {
    if (MDC.get(key) == null)
        MDC.put(key, value);
}