本文整理汇总了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);
}