本文整理匯總了Java中org.slf4j.MDC.put方法的典型用法代碼示例。如果您正苦於以下問題:Java MDC.put方法的具體用法?Java MDC.put怎麽用?Java MDC.put使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.slf4j.MDC
的用法示例。
在下文中一共展示了MDC.put方法的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: updateCurrentTerm
import org.slf4j.MDC; //導入方法依賴的package包/類
public void updateCurrentTerm(@Nonnegative long term) {
checkArgument(term >= 0);
MDC.put("term", Long.toString(term));
LOGGER.debug("New term {}", term);
setCurrentTerm(term);
try {
LogProto.JournalEntry entry = LogProto.JournalEntry.newBuilder().setTerm(LogProto.Term.newBuilder().setTerm(term)).build();
journal.write(entry.toByteArray(), WriteType.SYNC);
} catch (IOException e) {
Throwables.propagate(e);
}
}
示例3: doFilter
import org.slf4j.MDC; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest servletRequest = (HttpServletRequest) request;
String requestId = servletRequest.getHeader(X_OBOS_REQUEST_ID);
if (requestId == null || requestId.isEmpty()) {
requestId = UUID.randomUUID().toString();
}
try {
MDC.put(X_OBOS_REQUEST_ID, requestId);
chain.doFilter(request, response);
} finally {
MDC.remove(X_OBOS_REQUEST_ID);
}
}
示例4: 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);
}
}
示例5: 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);
}
}
示例6: doFilter
import org.slf4j.MDC; //導入方法依賴的package包/類
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 目前隻生成線程編號.
Trace trace = new Trace();
SystemContext.setTrace(trace.getThreadTrace());
MDC.put("Trace", SystemContext.getTrace());
System.out.println(" filer is running ");
filterChain.doFilter(request, response);
MDC.clear();
SystemContext.clean();
}
示例7: process
import org.slf4j.MDC; //導入方法依賴的package包/類
public void process(Exchange exchange) throws Exception {
String key = (String)exchange.getIn().getHeader(WebsocketConstants.CONNECTION_KEY);
MDC.clear();
MDC.put("WebsocketConstants.CONNECTION_KEY",key);
logger.info("Headers: {}",exchange.getIn().getHeaders());
}
示例8: inspect
import org.slf4j.MDC; //導入方法依賴的package包/類
/**
* @see org.atmosphere.cpr.AtmosphereInterceptor#inspect(org.atmosphere.cpr.AtmosphereResource)
*/
@Override
public Action inspect(final AtmosphereResource atmosphereResource) {
try {
SecurityContext context = (SecurityContext) atmosphereResource.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
final Authentication auth = context.getAuthentication();
if (auth instanceof Authentication) {
MDC.put(UserMdcServletFilter.USER_KEY, auth.getName());
logger.trace("Username set in MDC");
}
} catch (final NullPointerException e) {}
return Action.CONTINUE;
}
示例9: mdc_context_should_be_propagated
import org.slf4j.MDC; //導入方法依賴的package包/類
@Test
public void mdc_context_should_be_propagated() throws InterruptedException, ExecutionException {
// ExecutorService executorService = Executors.newFixedThreadPool(4);
ExecutorService executorService = new ThreadPoolTaskExecutorWithMdcPropagation(4, 4, 50, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
List<Future<String>> futures = new ArrayList<Future<String>>();
List<String> expectedTasks = new ArrayList<>();
for(int i=0; i<100; i++) {
MDC.put("requestId", "task"+i);
expectedTasks.add("task"+i);
futures.add(executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(100);
return MDC.get("requestId");
}
}));
}
for(Future<String> f : futures) {
String t = f.get();
if(!expectedTasks.remove(t)) {
Assert.fail("Unexpected task: "+t);
}
}
if(!expectedTasks.isEmpty()) {
Assert.fail("Expected tasks not returned: "+expectedTasks);
}
}
開發者ID:Orange-OpenSource,項目名稱:orange-mathoms-logging,代碼行數:29,代碼來源:ThreadPoolTaskExecutorWithMdcPropagationTest.java
示例10: 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;
}
示例11: prepareTestInstance
import org.slf4j.MDC; //導入方法依賴的package包/類
@Override
public void prepareTestInstance(TestContext testContext) {
MDC.put("Trace", UUID.randomUUID().toString());
}
示例12: setRequestId
import org.slf4j.MDC; //導入方法依賴的package包/類
public static void setRequestId(String requestId) {
MDC.put(FIELD_REQUEST_ID, requestId);
}
示例13: doBasicProfiling
import org.slf4j.MDC; //導入方法依賴的package包/類
@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));
}
}
示例14: put
import org.slf4j.MDC; //導入方法依賴的package包/類
public static void put(String key, String value) {
MDC.put(key, (value == null) ? generateRid() : value);
MDC.put(key + TIME, String.valueOf(System.nanoTime()));
}
示例15: addContextToMdc
import org.slf4j.MDC; //導入方法依賴的package包/類
public static void addContextToMdc(final String id, final String issuer) {
MDC.put("messageId", id);
MDC.put("entityId", issuer);
logPrefix("AuthnRequest", id, issuer);
}