当前位置: 首页>>代码示例>>Java>>正文


Java MDC.remove方法代码示例

本文整理汇总了Java中org.slf4j.MDC.remove方法的典型用法代码示例。如果您正苦于以下问题:Java MDC.remove方法的具体用法?Java MDC.remove怎么用?Java MDC.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.slf4j.MDC的用法示例。


在下文中一共展示了MDC.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: channelRead

import org.slf4j.MDC; //导入方法依赖的package包/类
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  MDC.put("node", node.getId().toString());

  try {
    if (msg instanceof Frame) {
      Frame frame = (Frame) msg;
      node.handle(ctx, frame);
    } else if (msg instanceof UnsupportedProtocolVersionMessage) {
      UnsupportedProtocolVersionMessage umsg = (UnsupportedProtocolVersionMessage) msg;
      node.handle(ctx, umsg);
    } else {
      throw new IllegalArgumentException("Received Invalid message into handler: " + msg);
    }
  } finally {
    MDC.remove("node");
  }
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:19,代码来源:RequestHandler.java

示例2: initChannel

import org.slf4j.MDC; //导入方法依赖的package包/类
@Override
protected void initChannel(Channel channel) throws Exception {
  ChannelPipeline pipeline = channel.pipeline();
  BoundNode node = channel.parent().attr(HANDLER).get();
  node.clientChannelGroup.add(channel);
  MDC.put("node", node.getId().toString());

  try {
    logger.debug("Got new connection {}", channel);

    pipeline
        .addLast("decoder", new FrameDecoder(node.getFrameCodec()))
        .addLast("encoder", new FrameEncoder(node.getFrameCodec()))
        .addLast("requestHandler", new RequestHandler(node));
  } finally {
    MDC.remove("node");
  }
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:19,代码来源:Server.java

示例3: runTestCase

import org.slf4j.MDC; //导入方法依赖的package包/类
@Override
public TestCaseResult runTestCase(String serviceName, String testName, String mode) {
    MDC.put(APP_NAME, RedirectorConstants.Logging.APP_NAME_PREFIX + serviceName);
    TestMode testMode = TestMode.valueOf(mode.toUpperCase());
    RedirectorTestCase testCase = getTestCase(serviceName, testName);
    if (testCase == null) {
        throw new WebApplicationException(Response.Status.NOT_FOUND); // test case not found
    }

    IRedirectorEnvLoader envLoader = getZookeeperRedirectorEnvLoader(serviceName, testMode);

    SelectServer flavorRules = envLoader.getFlavorRules();
    URLRules urlRules = envLoader.getUrlRules();
    Whitelisted whitelisted = envLoader.getWhitelists();
    NamespacedListRepository namespacedLists = new SimpleNamespacedListsHolder(envLoader.getNamespacedListsBatch());
    IRedirectorEngine engine = redirectorEngineFactory.newRedirectorEngine(
            serviceName, flavorRules, urlRules, whitelisted, namespacedLists, envLoader.getStacks(), new RedirectorEngine.SessionLog());
    Context context = TestSuiteUtils.getRedirectorContext(testCase);
    InstanceInfo instanceInfo = engine.redirect(context.asMap());

    TestSuiteResponse actual = TestSuiteUtils.getRedirectorResponse(instanceInfo);
    TestCaseResult testCaseResult = new TestCaseResult();
    testCaseResult.setStatus(TestCaseResult.Status.fromTestCase(testCase.getExpected(), actual));
    testCaseResult.setActual(actual);
    testCaseResult.setLogs(AutoTestRunner.getSessionLogs(context, engine));
    MDC.remove(APP_NAME);
    return testCaseResult;
}
 
开发者ID:Comcast,项目名称:redirector,代码行数:29,代码来源:RedirectorTestSuiteService.java

示例4: applySslSocketFactory

import org.slf4j.MDC; //导入方法依赖的package包/类
void applySslSocketFactory(OkHttpClient.Builder builder)
    throws FeatureException {

  try {
    MDC.put("security_context", "[security_support]");
    if (certificatePath == null) {
      logger.info("no custom certificate path supplied, using system default");
      return;
    }

    builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
    logger.info("ok, custom socket factory and trust manager added to builder");
  } finally {
    MDC.remove("security_context");
  }
}
 
开发者ID:dehora,项目名称:outland,代码行数:17,代码来源:CertificateLoader.java

示例5: doFilter

import org.slf4j.MDC; //导入方法依赖的package包/类
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	if (request instanceof HttpServletRequest) {
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		if (session != null) {
			// attach to MDC context
			MDC.put(mdcName, session.getId());
		}
	}

	try {
		chain.doFilter(request, response);
	} finally {
		// detach from MDC context
		MDC.remove(mdcName);
	}
}
 
开发者ID:Orange-OpenSource,项目名称:orange-mathoms-logging,代码行数:17,代码来源:SessionIdFilter.java

示例6: handleMessage

import org.slf4j.MDC; //导入方法依赖的package包/类
private void handleMessage(MessageHandler handler, Message message, Session session) {
    if (! (message instanceof TextMessage)) {
        return;
    }
    TextMessage textMessage = (TextMessage) message;
    String text = null;
    String requestId = UUID.randomUUID().toString();
    try {
        text = textMessage.getText();
        if (StringUtils.isNotEmpty(message.getJMSCorrelationID())) {
            requestId = message.getJMSCorrelationID();
        }

        MDC.put(X_OBOS_REQUEST_ID, requestId);

        log.info("Received message '{}'", text);

        handler.handle(new ObjectMapper().readTree(text));
    } catch (Exception e) {
        log.error("Failed to process message", e);
        try {
            TextMessage errorMessage = session.createTextMessage(text);
            errorMessage.setJMSCorrelationID(requestId);

            Queue queue = session.createQueue(queueError);
            MessageProducer errorProducer = session.createProducer(queue);
            errorProducer.send(errorMessage);
        } catch (JMSException jmse) {
            log.error("Failed to create error message", jmse);
        }
    } finally {
        MDC.remove(X_OBOS_REQUEST_ID);
    }
}
 
开发者ID:code-obos,项目名称:servicebuilder,代码行数:35,代码来源:ActiveMqListener.java

示例7: doFilter

import org.slf4j.MDC; //导入方法依赖的package包/类
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	// retrieve userId and set
	if (request instanceof HttpServletRequest) {
		Principal principal = ((HttpServletRequest) request).getUserPrincipal();
		if (principal != null) {
			String ppal = principal.getName();
			if (hashAlgorithm == null || "none".equalsIgnoreCase(hashAlgorithm)) {
				// no hash
			} else if ("hashcode".equalsIgnoreCase(hashAlgorithm)) {
				// simply hashcode
				ppal = Strings.padStart(Integer.toHexString(ppal.hashCode()), 8, '0');
			} else {
				// hexadecimal hash
				try {
					MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
					ppal = BaseEncoding.base16().encode(digest.digest(ppal.getBytes()));
				} catch (NoSuchAlgorithmException e) {
					throw new ServletException(e);
				}
			}
			// add to MDC and request attribute
			MDC.put(mdcName, ppal);
			request.setAttribute(attributeName, ppal);
		}
	}

	try {
		chain.doFilter(request, response);
	} finally {
		MDC.remove(mdcName);
	}
}
 
开发者ID:Orange-OpenSource,项目名称:orange-mathoms-logging,代码行数:33,代码来源:PrincipalFilter.java

示例8: commit

import org.slf4j.MDC; //导入方法依赖的package包/类
public void commit(DbLoadContext context) {
    // 成功时记录一下
    boolean dumpThisEvent = context.getPipeline().getParameters().isDumpEvent()
                            || context.getPipeline().getParameters().isDryRun();
    if (dump && dumpThisEvent && logger.isInfoEnabled()) {
        synchronized (LogLoadInterceptor.class) {
            try {
                MDC.put(OtterConstants.splitPipelineLoadLogFileKey,
                        String.valueOf(context.getIdentity().getPipelineId()));
                logger.info(SEP + "****************************************************" + SEP);
                logger.info(dumpContextInfo("successed", context));
                logger.info("****************************************************" + SEP);
                logger.info("* process Data  *" + SEP);
                logEventDatas(context.getProcessedDatas());
                logger.info("-----------------" + SEP);
                logger.info("* failed Data *" + SEP);
                logEventDatas(context.getFailedDatas());
                logger.info("****************************************************" + SEP);
            } finally {
                MDC.remove(OtterConstants.splitPipelineLoadLogFileKey);
            }
        }
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:25,代码来源:LogLoadInterceptor.java

示例9: error

import org.slf4j.MDC; //导入方法依赖的package包/类
public void error(DbLoadContext context) {
    boolean dumpThisEvent = context.getPipeline().getParameters().isDumpEvent()
                            || context.getPipeline().getParameters().isDryRun();
    if (dump && dumpThisEvent && logger.isInfoEnabled()) {
        synchronized (LogLoadInterceptor.class) {
            try {
                MDC.put(OtterConstants.splitPipelineLoadLogFileKey,
                        String.valueOf(context.getIdentity().getPipelineId()));
                logger.info(dumpContextInfo("error", context));
                logger.info("* process Data  *" + SEP);
                logEventDatas(context.getProcessedDatas());
                logger.info("-----------------" + SEP);
                logger.info("* failed Data *" + SEP);
                logEventDatas(context.getFailedDatas());
                logger.info("****************************************************" + SEP);
            } finally {
                MDC.remove(OtterConstants.splitPipelineLoadLogFileKey);
            }
        }
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:22,代码来源:LogLoadInterceptor.java

示例10: startJobs

import org.slf4j.MDC; //导入方法依赖的package包/类
/** 
 * Run the jobs that are scheduled to run in the next X seconds.
 */
private void startJobs() {
	List<String> runCache = new ArrayList<>();
	MDC.put("yadaThreadLevel", "info"); // Increase the log level to info so that you can remove sql dumps when in debug mode.
	List<? extends YadaJob> jobsToRun = yadaJobSchedulerDao.internalFindJobsToRun();
	MDC.remove("yadaThreadLevel");
	log.debug("Found {} job candidates to run", jobsToRun.size());
	// The list contains all candidate jobs for any jobGroup.
	for (YadaJob candidate : jobsToRun) {
		String candidateGroup = candidate.getJobGroup();
		if (runCache.contains(candidateGroup)) {
			continue; // We just started a job in this group, which can't be of lower priority because of the query order
		}
		// Check if a job of the same group is already running
		YadaJob running = yadaJobRepository.findRunning(candidateGroup);
		if (running!=null) {
			// If a job is already running, compare the priority for preemption
			if (running.getJobPriority()<candidate.getJobPriority()) {
				// Preemption
				interruptJob(running.getId());
			} else if (jobIsRunning(running.getId())) {
				runCache.add(candidateGroup); // The running job has higher priority and is actually running, so no other job in the group can have a higher priority because of the query order
				continue; // Next candidate
			}
		}
		// Either there was no running job or it has been preempted
		runJob(candidate.getId());
		runCache.add(candidateGroup);
	}
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:33,代码来源:YadaJobScheduler.java

示例11: doFilterInternal

import org.slf4j.MDC; //导入方法依赖的package包/类
/**
 * Forwards the request to the next filter in the chain and delegates down to the subclasses to perform the actual
 * request logging both before and after the request is processed.
 *
 * @see #beforeRequest
 * @see #afterRequest
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	if (resourceUrlStart==null) {
		resourceUrlStart = request.getContextPath() + YadaWebConfig.getResourceFolder() + "-"; // /site/res-
	}
	boolean isFirstRequest = !isAsyncDispatch(request);
	long startTime = -1;
	String sessionId = "";
	String username = "";
	// Questo codice per il calcolo dell'IP è stato messo in YadaWebUtil ma accedere quello da qui non viene facile, per cui duplico qui
	String remoteAddr = request.getRemoteAddr();
	String forwardedFor = request.getHeader("X-Forwarded-For");
	String remoteIp = "?";
	if (!StringUtils.isBlank(remoteAddr)) {
		remoteIp = remoteAddr;
	}
	if (!StringUtils.isBlank(forwardedFor)) {
		remoteIp = "[for " + forwardedFor + "]";
	}
	//
	String requestUri = request.getRequestURI();
	HttpSession session = request.getSession(false);
	SecurityContext securityContext = null;
	if (session!=null) {
		sessionId = StringUtils.trimToEmpty(session.getId());
		securityContext = ((SecurityContext)session.getAttribute("SPRING_SECURITY_CONTEXT"));
	}
	if (sessionId.length()==0) {
		sessionId = "req-"+Integer.toString(request.hashCode());
	}
	if (securityContext!=null) {
		try {
			username = securityContext.getAuthentication().getName();
		} catch (Exception e) {
			log.debug("No username in securityContext");
		}
	}
	MDC.put(MDC_SESSION, sessionId); // Session viene messo sull'MDC. Usarlo con %X{session} nel pattern
	MDC.put(MDC_USERNAME, username); // username viene messo sull'MDC. Usarlo con %X{username} nel pattern		
	MDC.put(MDC_REMOTEIP, remoteIp); // remoteIp viene messo sull'MDC. Usarlo con %X{remoteIp} nel pattern		

	if (isFirstRequest) {
		beforeRequest(request);
		startTime = System.currentTimeMillis();
	}
	try {
		filterChain.doFilter(request, response);
		int status = response.getStatus();
		if (!skipDuration(requestUri) && !isAsyncStarted(request)) {
			if (startTime>-1) {
				long timetaken = System.currentTimeMillis()-startTime;
				log.info("{}: {} ms (HTTP {})", requestUri, timetaken, status);
			}
		} else if (status>399) {
			log.error("{} HTTP {}", requestUri, status);
		}
	} finally {
		MDC.remove(MDC_USERNAME);
		MDC.remove(MDC_SESSION);
		MDC.remove(MDC_REMOTEIP);
	}
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:70,代码来源:AuditFilter.java

示例12: removeProperty

import org.slf4j.MDC; //导入方法依赖的package包/类
public static void removeProperty(IoSession session, String key) {
    if (key == null) {
        throw new IllegalArgumentException("key should not be null");
    }
    Map<String, String> context = getContext(session);
    context.remove(key);
    MDC.remove(key);
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:9,代码来源:MdcInjectionFilter.java

示例13: doPost

import org.slf4j.MDC; //导入方法依赖的package包/类
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    logger.debug("Handling json request");

    GoTimer methodTimer = null;
    String methodName = null;
    Span span = null;
    long startTime = System.nanoTime();
    Map<String, String> headers = gatherHttpHeaders(req);
    OrangeContext context = new OrangeContext(headers);
    try {

        MDC.put(CORRELATION_ID, context.getCorrelationId());

        String postedContent = CharStreams.toString(req.getReader());
        logger.debug("Request JSON: {}", postedContent);

        JsonRpcRequest rpcRequest;

        try {
            rpcRequest = parseRpcRequest(postedContent);
        } catch (IllegalArgumentException iaex) {
            logger.warn("Error parsing request: " + postedContent, iaex);
            @SuppressWarnings("ThrowableNotThrown")
            RpcCallException callException = new RpcCallException(RpcCallException.Category.BadRequest,
                    iaex.getMessage());
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.add(ERROR_FIELD, callException.toJson());
            writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, jsonResponse.toString());
            incrementFailureCounter("unknown", context.getRpcOriginService(),
                    context.getRpcOriginMethod());
            return;
        }

        methodName = rpcRequest.getMethod();

        span = getSpan(methodName, headers, context);

        methodTimer = getMethodTimer(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
        startTime = methodTimer.start();
        context.setCorrelationId(rpcRequest.getIdAsString());
        JsonRpcResponse finalResponse = dispatchJsonRpcRequest(rpcRequest, context);

        resp.setContentType(TYPE_JSON);
        writeResponse(resp, finalResponse.getStatusCode(), finalResponse.toJson().toString());

        //TODO: should we check the response for errors (for metrics)?
        methodTimer.recordSuccess(startTime);
        incrementSuccessCounter(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
    } catch (IOException e) {
        if (span != null) {
            Tags.ERROR.set(span, true);
        }
        //TODO: this case doesn't return a response.  should it?
        methodTimer.recordFailure(startTime);
        logger.error("Error handling request", e);
        incrementFailureCounter(methodName, context.getRpcOriginService(),
                context.getRpcOriginMethod());
    } finally {
        if (span != null) {
            span.finish();
        }
        MDC.remove(CORRELATION_ID);
    }
}
 
开发者ID:Sixt,项目名称:ja-micro,代码行数:67,代码来源:JsonHandler.java

示例14: read

import org.slf4j.MDC; //导入方法依赖的package包/类
@Override
public Page<Artifact, Artifact> read()
		throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
	MDC.remove(PATIENT);
	Page<Artifact, Artifact> page = super.read();
	while (page != null) {
		Artifact patient = page.getKey().get();
		if (patient.getFile() == null) {
			LOGGER.info("Skip {} as it is not fetched", patient);
			page = super.read();
			continue;
		}
		if (!patient.getExtension().equals("jar")) {
			LOGGER.info("Skip {} as it is not packaged as jar", patient);
			page = super.read();
			continue;
		}
		if (patient.isSnapshot()) {
			LOGGER.info("Skip {} as it is snapshot", patient);
			page = super.read();
			continue;
		}
		LOGGER.info("Processing {}...", patient);
		MDC.put(PATIENT, patient.toString());
		return page;
	}
	return null;
}
 
开发者ID:maenu,项目名称:kowalski,代码行数:29,代码来源:Reader.java

示例15: clearContext

import org.slf4j.MDC; //导入方法依赖的package包/类
public void clearContext() {
    operationContext.remove();
    MDC.remove("session");
    MDC.remove("opId");
    MDC.remove("command");
    MDC.remove("request");
}
 
开发者ID:kloiasoft,项目名称:eventapis,代码行数:8,代码来源:OperationContext.java


注:本文中的org.slf4j.MDC.remove方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。