本文整理汇总了Java中org.slf4j.MDC类的典型用法代码示例。如果您正苦于以下问题:Java MDC类的具体用法?Java MDC怎么用?Java MDC使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MDC类属于org.slf4j包,在下文中一共展示了MDC类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handler
import org.slf4j.MDC; //导入依赖的package包/类
public void handler(CloudwatchEvent event) throws ExecutionException, InterruptedException {
LOG.info("Received event = [{}]", event.getId());
final Metrics metrics = new Metrics();
// Pass Mapped Diagnostic Context (MDC) into child thread, for logging Request ID
final Map<String, String> contextMap = MDC.getCopyOfContextMap();
Runnable task = () -> {
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
LOG.info("Starting fibonacci task");
timedFibonacci(metrics);
};
// Start one task in the background, and one in this thread
Future<?> future = executorService.submit(task);
task.run();
// Wait for background task, log out metrics
future.get();
metrics.report(LOG);
}
示例2: 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");
}
}
示例3: doFilter
import org.slf4j.MDC; //导入依赖的package包/类
/**
* Sets the slf4j <code>MDC</code> and delegates the request to the chain.
*
* @param request servlet request.
* @param response servlet response.
* @param chain filter chain.
*
* @throws IOException thrown if an IO error occurrs.
* @throws ServletException thrown if a servet error occurrs.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
MDC.clear();
String hostname = HostnameFilter.get();
if (hostname != null) {
MDC.put("hostname", HostnameFilter.get());
}
Principal principal = ((HttpServletRequest) request).getUserPrincipal();
String user = (principal != null) ? principal.getName() : null;
if (user != null) {
MDC.put("user", user);
}
MDC.put("method", ((HttpServletRequest) request).getMethod());
MDC.put("path", ((HttpServletRequest) request).getPathInfo());
chain.doFilter(request, response);
} finally {
MDC.clear();
}
}
示例4: 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);
}
}
示例5: 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);
}
}
示例6: 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");
}
}
示例7: testPutRid
import org.slf4j.MDC; //导入依赖的package包/类
@Test
public void testPutRid() {
assertNull(MDCUtil.getRid());
MDCUtil.put("key", "value");
assertEquals("value", MDC.get("key"));
assertNull(MDCUtil.getRid());
MDCUtil.putRid("myRid");
assertEquals("myRid", MDCUtil.getRid());
assertEquals("myRid", MDC.get("rid"));
MDCUtil.clear();
assertNull(MDCUtil.getRid());
assertNull(MDC.get("key"));
}
示例8: 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;
}
示例9: getCorrelationId
import org.slf4j.MDC; //导入依赖的package包/类
@Override
public String getCorrelationId() {
HttpHeaders headers = ResteasyProviderFactory.getContextData(HttpHeaders.class);
String correlationId;
if (headers != null) {
correlationId = headers.getHeaderString(headerName);
if (correlationId != null) {
return correlationId;
}
}
// Fall back to MDC to support beadledom-jaxrs 1.0. Retrieving from the headers is preferred.
correlationId = MDC.get(mdcName);
return correlationId;
}
示例10: setupMyId
import org.slf4j.MDC; //导入依赖的package包/类
private void setupMyId() throws IOException {
File myIdFile = new File(dataDir, "myid");
// standalone server doesn't need myid file.
if (!myIdFile.isFile()) {
return;
}
BufferedReader br = new BufferedReader(new FileReader(myIdFile));
String myIdString;
try {
myIdString = br.readLine();
} finally {
br.close();
}
try {
serverId = Long.parseLong(myIdString);
MDC.put("myid", myIdString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("serverid " + myIdString
+ " is not a number");
}
}
示例11: call
import org.slf4j.MDC; //导入依赖的package包/类
public T call() throws Exception {
MDC.setContextMap(contextMap);
try {
return target.call();
}
finally {
MDC.clear();
}
}
示例12: doFilter
import org.slf4j.MDC; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
String requestId = req.getHeader(REQUEST_ID_HEADER);
requestId = (StringUtils.isBlank(requestId)) ? generateRequestId() : requestId;
String keycloakToken = req.getHeader(AUTHORIZATION_HEADER);
String identityId = getIdentityId(keycloakToken);
MDC.put(REQUEST_ID_MDC_KEY, requestId);
MDC.put(IDENTITY_ID_MDC_KEY, identityId);
chain.doFilter(request, response);
} finally {
MDC.clear();
}
}
示例13: testMdc
import org.slf4j.MDC; //导入依赖的package包/类
@Test
public void testMdc() throws Exception {
MDC.put("mdc-var1", "mdc-oldval");
SmartLog.start(output)
.pushMDC("mdc-var1", "mdc-val1")
.pushMDC("mdc-var2", "mdc-val2");
assertThat(MDC.get("mdc-var1")).isEqualTo("mdc-val1");
assertThat(MDC.get("mdc-var2")).isEqualTo("mdc-val2");
SmartLog.finish();
assertThat(MDC.get("mdc-var1")).isEqualTo("mdc-oldval");
assertThat(MDC.get("mdc-var2")).isNull();
}
示例14: wrap
import org.slf4j.MDC; //导入依赖的package包/类
/**
* Simple wrapper which copies over the context (MDC and correlation) to the executing thread and
* logs uncaught exceptions
*/
public static Runnable wrap(Runnable in, Supplier<String> correlationIdProvider, Consumer<String> correlationIdSetter) {
final Optional<Map<String, String>> context = Optional.ofNullable(MDC.getCopyOfContextMap());
final Optional<String> korrelasjonsId = Optional.ofNullable(correlationIdProvider.get());
return () -> {
Optional<Map<String, String>> contextBackup = Optional.ofNullable(MDC.getCopyOfContextMap());
final Optional<String> backupKorrelasjonsId = Optional.ofNullable(correlationIdProvider.get());
context.ifPresent(MDC::setContextMap);
korrelasjonsId.ifPresent(correlationIdSetter);
try {
in.run();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw e;
} finally {
MDC.clear();
contextBackup.ifPresent(MDC::setContextMap);
backupKorrelasjonsId.ifPresent(correlationIdSetter);
}
};
}
示例15: 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());
}