org.slf4j.MDC.put()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(8.3k)|赞(0)|评价(0)|浏览(541)

本文整理了Java中org.slf4j.MDC.put()方法的一些代码示例,展示了MDC.put()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MDC.put()方法的具体详情如下:
包路径:org.slf4j.MDC
类名称:MDC
方法名:put

MDC.put介绍

[英]Put a diagnostic context value (the val parameter) as identified with the key parameter into the current thread's diagnostic context map. The key parameter cannot be null. The val parameter can be null only if the underlying implementation supports it.

This method delegates all work to the MDC of the underlying logging system.
[中]将用key参数标识的诊断上下文值(val参数)放入当前线程的诊断上下文映射中。key参数不能为空。val参数只能在基础实现支持时为空。
此方法将所有工作委托给底层日志系统的MDC。

代码示例

代码示例来源:origin: ch.qos.logback/logback-classic

void insertIntoMDC(ServletRequest request) {
  MDC.put(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY, request.getRemoteHost());
  if (request instanceof HttpServletRequest) {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    MDC.put(ClassicConstants.REQUEST_REQUEST_URI, httpServletRequest.getRequestURI());
    StringBuffer requestURL = httpServletRequest.getRequestURL();
    if (requestURL != null) {
      MDC.put(ClassicConstants.REQUEST_REQUEST_URL, requestURL.toString());
    }
    MDC.put(ClassicConstants.REQUEST_METHOD, httpServletRequest.getMethod());
    MDC.put(ClassicConstants.REQUEST_QUERY_STRING, httpServletRequest.getQueryString());
    MDC.put(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY, httpServletRequest.getHeader("User-Agent"));
    MDC.put(ClassicConstants.REQUEST_X_FORWARDED_FOR, httpServletRequest.getHeader("X-Forwarded-For"));
  }
}

代码示例来源:origin: SonarSource/sonarqube

RequestIdMDCStorage(String requestId) {
 MDC.put(HTTP_REQUEST_ID_MDC_KEY, requireNonNull(requestId, "Request ID can't be null"));
}

代码示例来源:origin: alibaba/canal

@Override
  public void run() {
    boolean applyResult = false;
    try {
      MDC.put("destination", destination);
      applyResult = applySnapshotToDB(lastPosition, false);
    } catch (Throwable e) {
      logger.error("scheudle applySnapshotToDB faield", e);
    }
    try {
      MDC.put("destination", destination);
      if (applyResult) {
        snapshotExpire((int) TimeUnit.HOURS.toSeconds(snapshotExpire));
      }
    } catch (Throwable e) {
      logger.error("scheudle snapshotExpire faield", e);
    }
  }
}, snapshotInterval, snapshotInterval, TimeUnit.HOURS);

代码示例来源:origin: killbill/killbill

private void populateMDCContext(@Nullable final UUID userToken, @Nullable final Long accountRecordId, final Long tenantRecordId) {
  if (accountRecordId != null) {
    MDC.put(MDC_KB_ACCOUNT_RECORD_ID, String.valueOf(accountRecordId));
  }
  MDC.put(MDC_KB_TENANT_RECORD_ID, String.valueOf(tenantRecordId));
  MDC.put(MDC_KB_USER_TOKEN, userToken != null ? userToken.toString() : null);
}

代码示例来源:origin: apache/hive

private void setMDCFromNDC() {
 final Stack<String> clonedNDC = NDC.cloneStack();
 final String fragId = clonedNDC.pop();
 final String queryId = clonedNDC.pop();
 final String dagId = clonedNDC.pop();
 MDC.put("dagId", dagId);
 MDC.put("queryId", queryId);
 MDC.put("fragmentId", fragId);
}

代码示例来源:origin: MovingBlocks/Terasology

public static void setGameState(GameState state) {
    String phase = state.getLoggingPhase();
    phase = phase.replaceAll("\\s", "_");
    MDC.put(PHASE_KEY, phase);
  }
}

代码示例来源:origin: wildfly/wildfly

public Object putMdc(final String key, final Object value) {
  try {
    return MDC.get(key);
  } finally {
    if (value == null) {
      MDC.remove(key);
    } else {
      MDC.put(key, String.valueOf(value));
    }
  }
}

代码示例来源:origin: SonarSource/sonarqube

public void initForTask(CeTask task) {
 MDC.put(MDC_CE_TASK_UUID, task.getUuid());
}

代码示例来源:origin: apache/hive

/**
 * Register logging context so that log system can print QueryId, SessionId, etc for each message
 */
public static void registerLoggingContext(Configuration conf) {
 MDC.put(SESSIONID_LOG_KEY, HiveConf.getVar(conf, HiveConf.ConfVars.HIVESESSIONID));
 MDC.put(QUERYID_LOG_KEY, HiveConf.getVar(conf, HiveConf.ConfVars.HIVEQUERYID));
 if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_SERVER2_LOGGING_OPERATION_ENABLED)) {
  MDC.put(OPERATIONLOG_LEVEL_KEY, HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_SERVER2_LOGGING_OPERATION_LEVEL));
 }
}

代码示例来源:origin: alibaba/canal

public void handleDataDeleted(String dataPath) throws Exception {
  MDC.put("destination", destination);
  mutex.set(false);
  if (!release && activeData != null && isMine(activeData.getAddress())) {
    // 如果上一次active的状态就是本机,则即时触发一下active抢占
    initRunning();
  } else {
    // 否则就是等待delayTime,避免因网络瞬端或者zk异常,导致出现频繁的切换操作
    delayExector.schedule(new Runnable() {
      public void run() {
        initRunning();
      }
    }, delayTime, TimeUnit.SECONDS);
  }
}

代码示例来源:origin: alibaba/canal

public void stop() {
  super.stop();
  for (Map.Entry<String, CanalInstance> entry : canalInstances.entrySet()) {
    try {
      CanalInstance instance = entry.getValue();
      if (instance.isStart()) {
        try {
          String destination = entry.getKey();
          MDC.put("destination", destination);
          entry.getValue().stop();
          logger.info("stop CanalInstances[{}] successfully", destination);
        } finally {
          MDC.remove("destination");
        }
      }
    } catch (Exception e) {
      logger.error(String.format("stop CanalInstance[%s] has an error", entry.getKey()), e);
    }
  }
  metrics.terminate();
}

代码示例来源:origin: Activiti/Activiti

public static void putMDCExecution(ExecutionEntity e) {
 if (e.getId() != null)
  MDC.put(LOG_MDC_EXECUTION_ID, e.getId());
 if (e.getProcessDefinitionId() != null)
  MDC.put(LOG_MDC_PROCESSDEFINITION_ID, e.getProcessDefinitionId());
 if (e.getProcessInstanceId() != null)
  MDC.put(LOG_MDC_PROCESSINSTANCE_ID, e.getProcessInstanceId());
 if (e.getProcessInstanceBusinessKey() != null)
  MDC.put(LOG_MDC_BUSINESS_KEY, e.getProcessInstanceBusinessKey());
}

代码示例来源:origin: alibaba/canal

public void start(final String destination) {
  final CanalInstance canalInstance = canalInstances.get(destination);
  if (!canalInstance.isStart()) {
    try {
      MDC.put("destination", destination);
      if (metrics.isRunning()) {
        metrics.register(canalInstance);
      }
      canalInstance.start();
      logger.info("start CanalInstances[{}] successfully", destination);
    } finally {
      MDC.remove("destination");
    }
  }
}

代码示例来源:origin: alibaba/canal

public void stop(String destination) {
  CanalInstance canalInstance = canalInstances.remove(destination);
  if (canalInstance != null) {
    if (canalInstance.isStart()) {
      try {
        MDC.put("destination", destination);
        canalInstance.stop();
        if (metrics.isRunning()) {
          metrics.unregister(canalInstance);
        }
        logger.info("stop CanalInstances[{}] successfully", destination);
      } finally {
        MDC.remove("destination");
      }
    }
  }
}

代码示例来源:origin: alibaba/canal

public void handleDataDeleted(String dataPath) throws Exception {
  MDC.put("destination", destination);
  mutex.set(false);
  // 触发一下退出,可能是人为干预的释放操作或者网络闪断引起的session expired timeout
  processActiveExit();
  if (!release && activeData != null && isMine(activeData.getAddress())) {
    // 如果上一次active的状态就是本机,则即时触发一下active抢占
    initRunning();
  } else {
    // 否则就是等待delayTime,避免因网络瞬端或者zk异常,导致出现频繁的切换操作
    delayExector.schedule(new Runnable() {
      public void run() {
        initRunning();
      }
    }, delayTime, TimeUnit.SECONDS);
  }
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public void run() {
 MDC.put(ConfigurationKeys.TASK_KEY_KEY, task.getTaskKey());
 updateTaskMetrics();
}

代码示例来源:origin: alibaba/canal

public void handleDataChange(String dataPath, Object data) throws Exception {
  MDC.put("destination", destination);
  ServerRunningData runningData = JsonUtils.unmarshalFromByte((byte[]) data, ServerRunningData.class);
  if (!isMine(runningData.getAddress())) {
    mutex.set(false);
  }
  if (!runningData.isActive() && isMine(runningData.getAddress())) { // 说明出现了主动释放的操作,并且本机之前是active
    release = true;
    releaseRunning();// 彻底释放mainstem
  }
  activeData = (ServerRunningData) runningData;
}

代码示例来源:origin: alibaba/canal

public void handleDataChange(String dataPath, Object data) throws Exception {
  MDC.put("destination", destination);
  ClientRunningData runningData = JsonUtils.unmarshalFromByte((byte[]) data, ClientRunningData.class);
  if (!isMine(runningData.getAddress())) {
    mutex.set(false);
  }
  if (!runningData.isActive() && isMine(runningData.getAddress())) { // 说明出现了主动释放的操作,并且本机之前是active
    release = true;
    releaseRunning();// 彻底释放mainstem
  }
  activeData = (ClientRunningData) runningData;
}

代码示例来源:origin: org.apache.logging.log4j/log4j-slf4j-impl

@Test
public void mdc() {
  MDC.put("TestYear", "2010");
  logger.debug("Debug message");
  verify("List", "o.a.l.s.LoggerTest Debug message MDC{TestYear=2010}" + Strings.LINE_SEPARATOR);
  MDC.clear();
  logger.debug("Debug message");
  verify("List", "o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void clearForTask_removes_task_uuid_from_MDC() {
 MDC.put(MDC_CE_TASK_UUID, "some_value");
 underTest.clearForTask();
 assertThat(MDC.get(MDC_CE_TASK_UUID)).isNull();
}

相关文章