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

The following examples show how to use org.slf4j.MDC#remove() . 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: SLF4JSegmentListener.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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
    }
}
 
Example 2
Source File: BlackboxGradingEngine.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@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");
    }
}
 
Example 3
Source File: TestSessionManager.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
@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()));    
}
 
Example 4
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example 5
Source File: ClientAddressFilter.java    From qconfig with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example 6
Source File: CanalServerWithEmbedded.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
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");
            }
        }
    }
 
Example 7
Source File: DetectorManager.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 8
Source File: AuditLogger.java    From testcontainers-java with MIT License 6 votes vote down vote up
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");
}
 
Example 9
Source File: ConcurrentUpdateHttp2SolrClient.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
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");
  }
}
 
Example 10
Source File: IdentityIdLoggerFilter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 11
Source File: LogUtil.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * In the calling thread, stop book log annotation.
 */
public static void stopBook ()
{
    stopStub();

    if (!SwingUtilities.isEventDispatchThread()) {
        MDC.remove(BOOK);
    }
}
 
Example 12
Source File: MDCLoggingContext.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: ErrorToElasticsearchProcessor.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
@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 ...
    }
}
 
Example 14
Source File: ElasticsearchAdminService.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example 15
Source File: RequestLogFilter.java    From app-engine with Apache License 2.0 4 votes vote down vote up
@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();
        }
    }
}
 
Example 16
Source File: LoggingFilter.java    From webanno with Apache License 2.0 4 votes vote down vote up
public static void clearLoggingUsername()
{
    MDC.remove("_username");
    MDC.remove(Logging.KEY_USERNAME);
}
 
Example 17
Source File: BaseJavaDelegate.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example 18
Source File: SystemLogger.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
@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));
	}
}
 
Example 19
Source File: LogInterceptor.java    From molicode with Apache License 2.0 4 votes vote down vote up
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                            Object o, Exception e) throws Exception {
    MDC.remove(CommonConstant.SID);
    ThreadLocalHolder.clearRequestContext();
}
 
Example 20
Source File: TraceIdLogger.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
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);
}