@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"); } }
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); } }
@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); } }
@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"); } }
@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")); }
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); }
@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; }
/** * 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(); } }
@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; }
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"); } }
@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(); } }
@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(); }
/** * 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); } }; }
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()); }
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); } } } }
@Override public void afterTestMethod(TestContext testContext) { Method method = testContext.getTestMethod(); if (DataSetAnnotationUtils.isRun(method)) { try { MybatisTestProcessor mybatisTestProcessor = testContext. getApplicationContext().getBean(DataSetAnnotationUtils.getImplName(method)); boolean success = mybatisTestProcessor.compareResult(method); if (!success) { logger.info("Data test result : failure"); Assert.fail(); } } catch (EasyMallTestException e) { logger.error(e.getMessage(), e); Assert.fail(e.getMessage()); } } logger.info("Data test result : success"); MDC.clear(); }
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(); }
/** * @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; }
/** * Creates an error response with just the error code and description. The * request ID will be taken from the MDC. * * @param error * error code * @param errorDescription * error description */ public ErrorResponse(final String error, final String errorDescription) { this.error = error; this.errorDescription = errorDescription; requestId = MDC.get(REQUEST_ID); cause = null; errorClass = null; host = MDC.get(MDCKeys.HOST); jwtId = MDC.get(MDCKeys.JWT_ID); stackTrace = null; threadId = Thread.currentThread().getName(); requestUri = calculateRequestUri(); }
@Test public void thrownErrorWithMDC() { MDC.put(MDCKeys.REQUEST_ID, "abc"); MDC.put(MDCKeys.HOST, "localhost"); MDC.put(MDCKeys.REQUEST_URI, "http://hello"); MDC.put(MDCKeys.JWT_ID, "def"); final ErrorResponse response = new ErrorResponse(new IOException("ahem"), mock(UriInfo.class), true); assertNotNull(response.getStackTrace()); assertNull(response.getCause()); assertEquals(URI.create("http://hello"), response.getRequestUri()); assertEquals("abc", response.getRequestId()); assertEquals("def", response.getJwtId()); assertEquals("localhost", response.getHost()); }
/** * 执行数据分发工作 */ private void startProcessSelect() { executor.submit(new Runnable() { public void run() { MDC.put(OtterConstants.splitPipelineLogFileKey, String.valueOf(pipelineId)); String currentName = Thread.currentThread().getName(); Thread.currentThread().setName(createTaskName(pipelineId, "ProcessSelect")); try { processSelect(); } finally { Thread.currentThread().setName(currentName); MDC.remove(OtterConstants.splitPipelineLogFileKey); } } }); }
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); } }
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); } }
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); } } } }
@Override public void execute(DelegateExecution context) throws Exception { StepPhase stepPhase = null; createStepLogger(context); ExecutionWrapper executionWrapper = createExecutionWrapper(context); try { MDC.put(Constants.ATTR_CORRELATION_ID, StepsUtil.getCorrelationId(context)); getStepHelper().preExecuteStep(context, getInitialStepPhase(executionWrapper)); stepPhase = executeStep(executionWrapper); getStepHelper().failStepIfProcessIsAborted(context); LOGGER.debug("Execution finished"); } catch (MonitoringException | CloudFoundryException e) { getStepLogger().errorWithoutProgressMessage(e.getMessage()); stepPhase = getResultStepPhase(); handleException(context, e); } catch (Throwable t) { stepPhase = StepPhase.RETRY; handleException(context, t); } finally { StepsUtil.setStepPhase(executionWrapper, stepPhase); postExecuteStep(context, stepPhase); } }
@Override public K call() throws Exception { LOG.debug("Call using MDCHystrixContextCallable..."); Map childMDC = MDC.getCopyOfContextMap(); LOG.debug("childMDC --> " + childMDC); try { if (parentMDC != null) { MDC.setContextMap(parentMDC); } LOG.debug("parentMDC --> " + parentMDC); return actual.call(); } finally { if (childMDC != null) { MDC.setContextMap(childMDC); } } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if(principal instanceof User) { // ugly User user = (User) principal; MDC.put("userId", user.getId().toString()); } } chain.doFilter(request, response); } finally { MDC.clear(); } }
@Async("myTaskAsyncPool") public Future<Integer> doAsyncTask(String tableName, List<EventData> dataList, String destination) { try { MDC.put("destination", destination); logger.info("thread: " + Thread.currentThread().getName() + " is doing job :" + tableName); for (EventData eventData : dataList) { SpringUtil.doEvent(eventData.getPath(), eventData.getDbObject()); } } catch (Exception e) { logger.error("thread:" + Thread.currentThread().getName() + " get Exception", e); return new AsyncResult(0); } return new AsyncResult(1); }
@Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { String duration = "unknown"; try { Long requestStartTime = (Long)request.getProperty(START_TIME); if (requestStartTime != null && requestStartTime > 0) duration = Long.toString(System.currentTimeMillis() - requestStartTime); } catch (Exception x) { log.warn("Could not get request start time {}", x); } ArrayList<String> httpHeaders = getHeadersToLog(request); ArrayList<String> cookies = getCookiesToLog(request); String agent = request.getHeaderString(HttpHeaders.USER_AGENT); log.info("Request: {} {} agent={} status={} duration={} HTTP Headers={}, Cookies={}", request.getMethod(), getUrlToLog(request.getUriInfo().getRequestUri().toString()), agent, response.getStatus(), duration, httpHeaders, cookies); if (! "unknown".equals(duration)) { Metrics.reportWSApiCallDurationStats(agent, request.getUriInfo().getRequestUri().toString(), request.getMethod(), Long.parseLong(duration)); } if (response.getStatus() >= 400) { Metrics.reportWSFailedResponseStats(agent, request.getUriInfo().getRequestUri().toString(), request.getMethod()); } MDC.remove(USERNAME); }
private void startDetecting() { // 直接发送已追上的状态,保持和eromanga兼容处理 MainStemEventData mainStemData = new MainStemEventData(); mainStemData.setPipelineId(pipelineId); mainStemData.setStatus(MainStemEventData.Status.OVERTAKE); arbitrateEventService.mainStemEvent().single(mainStemData); // 启动异步线程定时监控,一定会有数据过来 String schedulerName = String.format("pipelineId = %s , CanalDetecting", String.valueOf(pipelineId)); scheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory(schedulerName)); future = scheduler.scheduleAtFixedRate(new Runnable() { public void run() { try { MDC.put(OtterConstants.splitPipelineLogFileKey, String.valueOf(pipelineId)); // 检查下和最后收到的数据的时间戳,如果超过一定时间没收到,说明canal解析存在问题 // (因为会有心跳包数据,理论上时间间隔会小于一定值) if (isDelayed(System.currentTimeMillis(), lastEventExecuteTime)) { notifyFailed(); } else { notifySuccessed(); } } catch (Exception e) { logger.error("heartbeat check failed!", e); } finally { MDC.remove(OtterConstants.splitPipelineLogFileKey); } } }, detectingIntervalInSeconds, detectingIntervalInSeconds, TimeUnit.SECONDS); }
@Override public void filter( ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MDC.remove(mdcName); String correlationId = (String) requestContext.getProperty(mdcName); if (correlationId == null) { // Can happen if there are oauth issues. correlationId = UUID.randomUUID().toString(); } responseContext.getHeaders().add(headerName, correlationId); }
public static void put(String key, String value) { MDC.put(key, (value == null) ? generateRid() : value); MDC.put(key + TIME, String.valueOf(System.nanoTime())); }
/** * コンストラクタ. * @param cell セル */ public PersoniumEventBus(final Cell cell) { this(); String unitUserName = getUnitUserName(cell.getOwner()); String prefix1 = cell.getId().substring(IDX_1ST_START, IDX_1ST_END); String prefix2 = cell.getId().substring(IDX_2ND_START, IDX_2ND_END); String path = String.format("%s/%s/%s/%s", unitUserName, prefix1, prefix2, cell.getId()); // MDCにCell名を設定 MDC.put("eventlog_path", path); }
static void queueMessage(Session session, String text, String queueName) { try { Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); TextMessage message = session.createTextMessage(text); message.setJMSCorrelationID(MDC.get(X_OBOS_REQUEST_ID)); producer.send(message); session.commit(); } catch (JMSException ex) { throw new MessageQueueException("Could not queue message '" + text + "'", ex); } }
public CustomMDCBreadCrumbIdUnitOfWork(Exchange exchange) { super(exchange); //Expecting "businessId" and generate one if missing. if (exchange.getIn().getHeader("businessId") == null) { exchange.getIn().setHeader("businessId",UUID.randomUUID().toString()); } MDC.put(MDC_BREADCRUMB_ID, exchange.getIn().getHeader("businessId",String.class)); }
private void stageChanged(final Long processId, final List<String> stages) { for (final StageListener listener : listeners) { // 异步处理 arbitrateExecutor.submit(new Runnable() { public void run() { MDC.put(ArbitrateConstants.splitPipelineLogFileKey, String.valueOf(getPipelineId())); listener.stageChannged(processId, stages); } }); } }