本文整理匯總了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");
}
}
示例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");
}
}
示例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;
}
示例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");
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
}
}
示例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);
}
}
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例15: clearContext
import org.slf4j.MDC; //導入方法依賴的package包/類
public void clearContext() {
operationContext.remove();
MDC.remove("session");
MDC.remove("opId");
MDC.remove("command");
MDC.remove("request");
}