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

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

源代码1 项目: aws-xray-sdk-java   文件: SLF4JSegmentListener.java
/**
 * Maps the AWS-XRAY-TRACE-ID key to the trace ID of the entity that's just been created in the MDC.
 * Does not perform injection if entity is not available or not sampled, since then the given entity would not be displayed
 * in X-Ray console.
 *
 * @param oldEntity the previous entity or null
 * @param newEntity the new entity, either a subsegment or segment
 */
@Override
public void onSetEntity(Entity oldEntity, Entity newEntity) {
    if (newEntity == null) {
        MDC.remove(TRACE_ID_KEY);
        return;
    }

    Segment segment =  newEntity instanceof Segment ? ((Segment) newEntity) : newEntity.getParentSegment();

    if (segment != null && segment.getTraceId() != null && segment.isSampled() && newEntity.getId() != null) {
        String fullPrefix = StringValidator.isNullOrBlank(this.prefix) ? "" : this.prefix + ": ";
        MDC.put(TRACE_ID_KEY, fullPrefix + segment.getTraceId() + "@" + newEntity.getId());
    } else {
        MDC.remove(TRACE_ID_KEY);  // Ensure traces don't spill over to unlinked messages
    }
}
 
源代码2 项目: testcontainers-java   文件: AuditLogger.java
public static void doComposeLog(@NotNull String[] commandParts,
                                @Nullable List<String> env) {

    if (! log.isTraceEnabled()) {
        return;
    }

    MDC.put(MDC_PREFIX + ".Action", "COMPOSE");

    if (env != null) {
        MDC.put(MDC_PREFIX + ".Compose.Env", env.toString());
    }

    final String command = StringUtils.join(commandParts, ' ');
    MDC.put(MDC_PREFIX + ".Compose.Command", command);

    log.trace("COMPOSE action with command: {}, env: {}", command, env);

    MDC.remove(MDC_PREFIX + ".Action");
    MDC.remove(MDC_PREFIX + ".Compose.Command");
    MDC.remove(MDC_PREFIX + ".Compose.Env");
}
 
源代码3 项目: adaptive-alerting   文件: DetectorManager.java
/**
 * Classifies the mapped metric data, performing detector lookup behind the scenes. Returns {@code null} if there's
 * no detector defined for the given mapped metric data.
 *
 * @param mappedMetricData Mapped metric data.
 * @return The anomaly result, or {@code null} if there's no associated detector.
 */
public DetectorResult detect(@NonNull MappedMetricData mappedMetricData) {
    try {
        MDC.put("DetectorUuid", mappedMetricData.getDetectorUuid().toString());
        checkMappedMetricData(mappedMetricData);
        Optional<DetectorContainer> container = getDetector(mappedMetricData);
        if (container.isPresent()) {
            Optional<DetectorResult> optionalDetectorResult = doDetection(container.get(), mappedMetricData.getMetricData());
            return optionalDetectorResult.orElse(null);
        } else {
            return null;
        }
    } finally {
        MDC.remove("DetectorUuid");
    }
}
 
源代码4 项目: canal-1.1.3   文件: CanalServerWithEmbedded.java
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);
                }
//                启动canal instance
                canalInstance.start();
                logger.info("start CanalInstances[{}] successfully", destination);
            } finally {
                MDC.remove("destination");
            }
        }
    }
 
源代码5 项目: qconfig   文件: ClientAddressFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String ip = RequestUtil.getRealIP(req);
    int port = Numbers.toInt(req.getHeader(Constants.PORT));

    try {
        clientInfoService.setIp(ip);
        clientInfoService.setPort(port);
        MDC.put(IP, ip);
        MDC.put(Constants.PORT, String.valueOf(port));

        filterChain.doFilter(request, servletResponse);
    } finally {
        clientInfoService.clear();
        MDC.remove(IP);
        MDC.remove(Constants.PORT);
    }
}
 
@Test
void testMdcPropertyPreservation() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> a.addBuiltIn(BuiltInProperty.REQ_DIRECTION));

    MDC.put("some-prop", "some-value");
    final ServiceRequestContext ctx = newServiceContext("/foo", null);
    try (SafeCloseable ignored = ctx.push()) {
        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("req.direction", "INBOUND")
                       .containsEntry("some-prop", "some-value")
                       .hasSize(2);
    } finally {
        MDC.remove("some-prop");
    }
}
 
源代码7 项目: HttpSessionReplacer   文件: TestSessionManager.java
@Test
public void testDisableSessionInMdc() {
  MDC.remove(configuration.getLoggingMdcKey());
  configuration.setLoggingMdcActive(false);
  SessionData sessionData = new SessionData("1", now(), 10);
  RepositoryBackedSession session = mock(RepositoryBackedSession.class);
  when(session.getId()).thenReturn("1");
  when(repository.getSessionData("1")).thenReturn(sessionData);
  when(factory.build(sessionData)).thenReturn(session);
  RequestWithSession request = mock(RequestWithSession.class);
  when(tracking.retrieveId(request)).thenReturn(new SessionTracking.IdAndSource("1", false));
  sessionManager.getSession(request, false, null);
  assertNull("Logging MDC should remain null", MDC.get(configuration.getLoggingMdcKey()));    
  MDC.put(configuration.getLoggingMdcKey(), "something");
  sessionManager.getSession(request, false, null);
  assertEquals("Logging MDC was changed", "something", MDC.get(configuration.getLoggingMdcKey()));    
  request = mock(RequestWithSession.class);
  sessionManager.getSession(request, false, null);
  assertEquals("Logging MDC was changed", "something", MDC.get(configuration.getLoggingMdcKey()));    
}
 
源代码8 项目: judgels   文件: BlackboxGradingEngine.java
@Override
public GradingResult grade(
        File gradingDir,
        GradingConfig config,
        GradingLanguage language,
        GradingSource source,
        SandboxFactory sandboxFactory) throws GradingException {

    this.gradingDir = gradingDir;
    this.config = config;
    this.language = language;
    this.source = source;
    this.sandboxFactory = sandboxFactory;

    try {
        return doGrade();
    } finally {
        cleanUp();

        MDC.remove("gradingPhase");
    }
}
 
源代码9 项目: lucene-solr   文件: MDCLoggingContext.java
private static void removeAll() {
  MDC.remove(COLLECTION_PROP);
  MDC.remove(CORE_NAME_PROP);
  MDC.remove(REPLICA_PROP);
  MDC.remove(SHARD_ID_PROP);
  MDC.remove(NODE_NAME_PROP);
  MDC.remove(TRACE_ID);
}
 
private void addRunner() {
  MDC.put("ConcurrentUpdateHttp2SolrClient.url", String.valueOf(client.getBaseURL())); // MDC can't have null value
  try {
    Runner r = new Runner();
    runners.add(r);
    try {
      scheduler.execute(r);  // this can throw an exception if the scheduler has been shutdown, but that should be fine.
    } catch (RuntimeException e) {
      runners.remove(r);
      throw e;
    }
  } finally {
    MDC.remove("ConcurrentUpdateHttp2SolrClient.url");
  }
}
 
源代码11 项目: che   文件: IdentityIdLoggerFilter.java
@Override
public final void doFilter(
    ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException {
  Subject subject = EnvironmentContext.getCurrent().getSubject();
  if (subject != null && subject.getUserId() != null) {
    MDC.put(IDENTITY_ID_MDC_KEY, subject.getUserId());
  }

  try {
    filterChain.doFilter(request, response);
  } finally {
    MDC.remove(IDENTITY_ID_MDC_KEY);
  }
}
 
源代码12 项目: audiveris   文件: LogUtil.java
/**
 * In the calling thread, stop book log annotation.
 */
public static void stopBook ()
{
    stopStub();

    if (!SwingUtilities.isEventDispatchThread()) {
        MDC.remove(BOOK);
    }
}
 
源代码13 项目: SkaETL   文件: ErrorToElasticsearchProcessor.java
@Override
protected void parseResultErrors(BulkRequest request, BulkResponse bulkItemResponses) {
    for (BulkItemResponse bir : bulkItemResponses) {
        MDC.put("item_error", bir.getFailureMessage());
        log.info("EsError" + bir.getFailureMessage());
        MDC.remove("item_error");
        //TODO ...
    }
}
 
源代码14 项目: SkaETL   文件: ElasticsearchAdminService.java
public void createAllIndex(Integer plusDay, String... listIndex) throws IOException {
    log.info("Creation Index");

    for (String index : listIndex) {
        LocalDateTime now = LocalDateTime.now();
        String indexToCreate = esConfiguration.getCustomIndexPrefix() + "-" + index + "-" + now.plusDays(plusDay).format(DateTimeFormatter.ISO_LOCAL_DATE);
        //CreateIndexRequest request = new CreateIndexRequest(indexToCreate);
        Response response = client.getLowLevelClient().performRequest("PUT", "/" + indexToCreate);
        MDC.put("creation_index_all", indexToCreate);
        log.info("creation index {} with response {}", indexToCreate, response);
        MDC.remove("creation_index_all");
    }
}
 
源代码15 项目: molicode   文件: LogInterceptor.java
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                            Object o, Exception e) throws Exception {
    MDC.remove(CommonConstant.SID);
    ThreadLocalHolder.clearRequestContext();
}
 
源代码16 项目: app-engine   文件: RequestLogFilter.java
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String path = request.getRequestURI();
    if (StringUtils.startsWithAny(path, "/webjars", "/static", "/js", "/css", "/libs", "/WEB-INF")
            || StringUtils.endsWithAny(path, GlobalConstants.staticResourceArray)) {
        filterChain.doFilter(request, response);
        return;
    }

    RequestContext context = ThreadLocalContext.getRequestContext();
    MDC.put("requestId", context.getRequestId());

    response = new ResponseWrapper(response);
    long startTime = System.currentTimeMillis();
    try {
        filterChain.doFilter(request, response);
    } catch (Exception e) {
        //此处拦截也必须抛出,否则不执行ErrorHandlerResource
        if (e instanceof EngineException) {
            logger.error("EngineException error", e.getMessage() + " " + ((EngineException) e).getErrorMsgCn());
        } else if (e.getCause() instanceof EngineException) {
            logger.error("EngineException error", e.getCause().getMessage() + " " + ((EngineException) e.getCause()).getErrorMsgCn());
        } else {
            logger.error("filterChain.doFilter error", e);
        }
        throw e;
    } finally {
        //如果是错误页面 或 没有错误的第一次执行
        if (StringUtils.equals("/error", path) || request.getAttribute("org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.ERROR") == null) {
            long endTime = System.currentTimeMillis();
            RequestLogRecord record = new RequestLogRecord();
            record.setRequestId(context.getRequestId());
            record.setIp(request.getRemoteHost());
            record.setUid(context.getCurrentUid());
            record.setSource(context.getAppId() + "");
            record.setUseTime(endTime - startTime);
            Object requestUri = request.getAttribute("javax.servlet.error.request_uri");
            record.setApi(requestUri != null ? (String) requestUri : path);
            record.setMethod(request.getMethod());
            record.setParameters(request.getParameterMap());
            record.setResponseStatus(response.getStatus());
            record.setClientVersion(context.getClientVersion());
            record.setResponse(new String(((ResponseWrapper) response).toByteArray(), response.getCharacterEncoding()));
            //text/html不打印body
            if (!StringUtils.contains(response.getContentType(), "application/json")) {
                record.setWriteBody(false);
            }
            MDC.put("CUSTOM_LOG", "request");
            logger.info(record.toString());
            MDC.remove("CUSTOM_LOG");
            ThreadLocalContext.clear();
        }
    }
}
 
源代码17 项目: webanno   文件: LoggingFilter.java
public static void clearLoggingUsername()
{
    MDC.remove("_username");
    MDC.remove(Logging.KEY_USERNAME);
}
 
源代码18 项目: herd   文件: BaseJavaDelegate.java
/**
 * This is what Activiti will call to execute this task. Sub-classes should override the executeImpl method to supply the actual implementation.
 *
 * @param execution the execution information.
 *
 * @throws Exception if any errors were encountered.
 */
@Override
public final void execute(DelegateExecution execution) throws Exception
{
    long taskBeginTimeMillis = 0;
    boolean taskSuccessFlag = false;
    try
    {
        // Need to clear the security context here since the current thread may have been reused,
        // which may might have left over its security context. If we do not clear the security
        // context, any subsequent calls may be restricted by the permissions given
        // to the previous thread's security context.
        SecurityContextHolder.clearContext();

        // Check if method is not allowed.
        configurationDaoHelper.checkNotAllowedMethod(this.getClass().getCanonicalName());

        // Set the security context per last updater of the current process instance's job definition.
        ApplicationUser applicationUser = getApplicationUser(execution);
        setSecurityContext(applicationUser);

        // Set the MDC property for the Activiti process instance ID and user ID.
        MDC.put(ACTIVITI_PROCESS_INSTANCE_ID_KEY, "activitiProcessInstanceId=" + execution.getProcessInstanceId());
        MDC.put(USER_ID_KEY, "userId=" + (applicationUser.getUserId() == null ? "" : applicationUser.getUserId()));

        // Log all input variables from the execution (before the execution starts).
        logInputParameters(execution);

        // Set the task begin time
        taskBeginTimeMillis = System.currentTimeMillis();

        // Perform the execution implementation handled in the sub-class.
        executeImpl(execution);

        // Set a success status as a workflow variable.
        activitiRuntimeHelper.setTaskSuccessInWorkflow(execution);

        // Set the flag to true since there is no exception thrown
        taskSuccessFlag = true;
    }
    catch (Exception ex)
    {
        handleException(execution, ex);
    }
    finally
    {
        // Log the task execution time
        logTaskExecutionTime(taskBeginTimeMillis, taskSuccessFlag);

        // Remove the MDC property to ensure they don't accidentally get used by anybody else.
        MDC.remove(ACTIVITI_PROCESS_INSTANCE_ID_KEY);
        MDC.remove(USER_ID_KEY);

        // Clear up the security context.
        SecurityContextHolder.clearContext();
    }
}
 
源代码19 项目: AsuraFramework   文件: SystemLogger.java
@Around("execution(* com..*.proxy..*.* (..))")
public Object doBasicProfiling(final ProceedingJoinPoint joinPoint) throws Throwable {
	long start_all = System.currentTimeMillis();
	long end_all = 0L;
	String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
	String signatureName = joinPoint.getSignature().getName();
	Object [] args = joinPoint.getArgs();
	Transaction tran = Cat.newTransaction("Aspect-proxy", declaringTypeName + "." + signatureName);
	if (RpcContext.getContext().getRemoteAddressString() != null && RpcContext.getContext().getMethodName() != null
			&& RpcContext.getContext().getUrl() != null) {
		MDC.put(HOST, RpcContext.getContext().getRemoteAddressString());
		MDC.put(INTERFACE, RpcContext.getContext().getUrl().getServiceInterface());
		MDC.put(METHOD, RpcContext.getContext().getMethodName());
	} else {
		MDC.put(HOST, "127.0.0.1");
		MDC.put(INTERFACE, "none");
		MDC.put(METHOD, "none");
	}

	final DataLogEntity de = new DataLogEntity();
	de.setClassName(declaringTypeName);
	de.setMethodName(signatureName);
	de.setParams(args);
	String logJson = de.toJsonStr();
	// 参数日志
	if (logger.isDebugEnabled()) {
		logger.debug(de.toJsonStr());
	}
	try {
		long start = System.currentTimeMillis();
		final Object retVal = joinPoint.proceed();
		long end = System.currentTimeMillis();
		// 记录耗时
		logger.info("{}, 耗时:{} ms, 进入aop到执行完耗时:{} ms", logJson, (end - start), (end - start_all));
		Cat.logEvent(declaringTypeName, signatureName, "0", logJson+" 耗时:" + (end - start) + " ms" + " 时间戳:" + System.currentTimeMillis());
		/**
		 * 设置消息的状态,必须设置,0:标识成功,其他标识发生了异常
		 */
		tran.setStatus(Transaction.SUCCESS);
		end_all = System.currentTimeMillis();
		return retVal;
	} catch (final Exception e) {
		final ErrorLogEntity ele = new ErrorLogEntity(de);
		DataTransferObject dto = handleException(e, ele, tran);
		end_all = System.currentTimeMillis();
		// 方法返回值类型
		Class returnType = null;
		if (null != joinPoint.getSignature()) {
			returnType = ((MethodSignature) joinPoint.getSignature()).getReturnType();
		}
		if (null != returnType && returnType.equals(String.class)){
			return dto.toJsonString();
		}else if (null != returnType && returnType.equals(DataTransferObject.class)){
			return dto;
		}else{
			throw e;
		}
	} finally {
		MDC.remove(HOST);
		MDC.remove(INTERFACE);
		MDC.remove(METHOD);
		tran.complete();
		logger.info("{}, 接入cat后整体耗时: {} ms", logJson, (end_all - start_all));
	}
}
 
源代码20 项目: servicecomb-java-chassis   文件: TraceIdLogger.java
public void info(Logger logger, String format, Object... arguments) {
  MDC.put(KEY_TRACE_ID, getName());
  logger.info(MARKER, format, arguments);
  MDC.remove(KEY_TRACE_ID);
}