public MDCUnitOfWork(Exchange exchange) { super(exchange, LOG); // remember existing values this.originalExchangeId = MDC.get(MDC_EXCHANGE_ID); this.originalMessageId = MDC.get(MDC_MESSAGE_ID); this.originalBreadcrumbId = MDC.get(MDC_BREADCRUMB_ID); this.originalCorrelationId = MDC.get(MDC_CORRELATION_ID); this.originalRouteId = MDC.get(MDC_ROUTE_ID); this.originalCamelContextId = MDC.get(MDC_CAMEL_CONTEXT_ID); this.originalTransactionKey = MDC.get(MDC_TRANSACTION_KEY); // must add exchange and message id in constructor MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId()); String msgId = exchange.hasOut() ? exchange.getOut().getMessageId() : exchange.getIn().getMessageId(); MDC.put(MDC_MESSAGE_ID, msgId); // the camel context id is from exchange MDC.put(MDC_CAMEL_CONTEXT_ID, exchange.getContext().getName()); // and add optional correlation id String corrId = exchange.getProperty(Exchange.CORRELATION_ID, String.class); if (corrId != null) { MDC.put(MDC_CORRELATION_ID, corrId); } // and add optional breadcrumb id String breadcrumbId = exchange.getIn().getHeader(Exchange.BREADCRUMB_ID, String.class); if (breadcrumbId != null) { MDC.put(MDC_BREADCRUMB_ID, breadcrumbId); } }
@Override public void requestInitialized(ServletRequestEvent sre) { if (corePlugin.isStagemonitorActive()) { final MeasurementSession measurementSession = corePlugin.getMeasurementSession(); if (measurementSession.getApplicationName() != null) { MDC.put("application", measurementSession.getApplicationName()); } if (measurementSession.getHostName() != null) { MDC.put("host", measurementSession.getHostName()); } String instanceName = measurementSession.getInstanceName(); if (instanceName == null) { instanceName = sre.getServletRequest().getServerName(); } MDC.put("instance", instanceName); final String requestId = UUID.randomUUID().toString(); sre.getServletRequest().setAttribute(STAGEMONITOR_REQUEST_ID_ATTR, requestId); if (Stagemonitor.isStarted()) { // don't store the requestId in MDC if stagemonitor is not active // so that thread pools that get created on startup don't inherit the requestId MDC.put("requestId", requestId); } } }
@Override protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { // MDCにメソッド呼び出し情報をセットする。 String beforeClassName = MDC.get(MDC_CLASS_NAME); String beforeMethodName = MDC.get(MDC_METHOD_NAME); MDC.put(MDC_CLASS_NAME, getClassForLogging(invocation.getThis()).getName()); MDC.put(MDC_METHOD_NAME, invocation.getMethod().getName()); try { return super.invokeUnderTrace(invocation, logger); } finally { // MDCのメソッド呼び出し情報を元に戻す。 if (beforeClassName == null) { MDC.remove(MDC_CLASS_NAME); } else { MDC.put(MDC_CLASS_NAME, beforeClassName); } if (beforeMethodName == null) { MDC.remove(MDC_METHOD_NAME); } else { MDC.put(MDC_METHOD_NAME, beforeMethodName); } } }
protected void logQuery(Logger logger, String queryString, Collection<Object> parameters) { String normalizedQuery = queryString.replace('\n', ' '); MDC.put(QueryBase.MDC_QUERY, normalizedQuery); MDC.put(QueryBase.MDC_PARAMETERS, String.valueOf(parameters)); if (logger.isDebugEnabled()) { logger.debug(normalizedQuery); } }
public static void addBotToMDC(PircBotX bot) { MDC.put("pircbotx.id", String.valueOf(bot.getBotId())); MDC.put( "pircbotx.connectionId", bot.getServerHostname() + "-" + bot.getBotId() + "-" + bot.getConnectionId()); MDC.put("pircbotx.server", StringUtils.defaultString(bot.getServerHostname())); MDC.put("pircbotx.port", String.valueOf(bot.getServerPort())); }
@Test public void testConvertWithMultipleEntries() { MDC.put("testKey", "testValue"); MDC.put("testKey2", "testValue2"); ILoggingEvent le = createLoggingEvent(); String result = converter.convert(le); boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?"); assertTrue(result + " is not conform", isConform); }
/** @see wicket.RequestCycle#onBeginRequest() */ @SuppressWarnings("nls") @Override protected void onBeginRequest() { WebClientSession webClientSession = (WebClientSession) getSession(); WebClient webClient = webClientSession.getWebClient(); if (webClient != null) { if (webClient.getSolution() != null) { MDC.put("clientid", webClient.getClientID()); MDC.put("solution", webClient.getSolution().getName()); } J2DBGlobals.setServiceProvider(webClient); webClient.onBeginRequest(webClientSession); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { Principal principal = ((HttpServletRequest) request).getUserPrincipal(); if (principal != null) { MDC.put(LogConstants.USER, principal.getName()); } else { MDC.put(LogConstants.USER, "?"); } chain.doFilter(request, response); } finally { MDC.clear(); } }
@Test public void mdc() throws EvaluationException { MDC.put("key", "val"); LoggingEvent event = makeEvent("x"); doEvaluateAndCheck("e.mdc['key'] == 'val'", event, true); MDC.clear(); }
/** * Wrapper around <code>MDC.put</code> and <code>MDC.remove</code>. <code>value</code> is allowed * to e null. */ private static void setMdc(String key, String value) { if (value != null) { MDC.put(key, value); } else { MDC.remove(key); } }
@Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { assert request != null; assert response != null; // Log the request URI+URL muck String uri = request.getRequestURI(); if (request.getQueryString() != null) { uri = String.format("%s?%s", uri, request.getQueryString()); } if (log.isDebugEnabled()) { log.debug( "Processing: {} {} ({}) [{}]", $(request.getMethod(), uri, request.getRequestURL(), request.getHeader(HUDSON_HEADER))); } MDC.put(getClass().getName(), uri); try { super.service(request, response); } finally { MDC.remove(getClass().getName()); } // Include the version details of the api + model response.addHeader(HUDSON_HEADER, String.format("api=%s", getApiVersion())); }
public Object step(int step) { helper.assertStep(step); try { MDC.put("fileset", logFilename); log.debug("Step " + step); Job j = activity.getChild(); if (j == null) { throw helper.cancel(new ERR(), null, "null-job"); } else if (!(j instanceof MetadataImportJob)) { throw helper.cancel(new ERR(), null, "unexpected-job-type", "job-type", j.ice_id()); } if (step == 0) { return importMetadata((MetadataImportJob) j); } else if (step == 1) { return pixelData(null); // (ThumbnailGenerationJob) j); } else if (step == 2) { return generateThumbnails(null); // (PixelDataJob) j); Nulls image } else if (step == 3) { // TODO: indexing and scripting here as well. store.launchProcessing(); return null; } else if (step == 4) { return objects; } else { throw helper.cancel(new ERR(), null, "bad-step", "step", "" + step); } } catch (MissingLibraryException mle) { notifyObservers(new ErrorHandler.MISSING_LIBRARY(fileName, mle, usedFiles, format)); throw helper.cancel(new ERR(), mle, "import-missing-library", "filename", fileName); } catch (UnsupportedCompressionException uce) { // Handling as UNKNOWN_FORMAT for 4.3.0 notifyObservers(new ErrorHandler.UNKNOWN_FORMAT(fileName, uce, this)); throw helper.cancel(new ERR(), uce, "import-unknown-format", "filename", fileName); } catch (UnknownFormatException ufe) { notifyObservers(new ErrorHandler.UNKNOWN_FORMAT(fileName, ufe, this)); throw helper.cancel(new ERR(), ufe, "import-unknown-format", "filename", fileName); } catch (IOException io) { notifyObservers(new ErrorHandler.FILE_EXCEPTION(fileName, io, usedFiles, format)); throw helper.cancel(new ERR(), io, "import-file-exception", "filename", fileName); } catch (FormatException fe) { notifyObservers(new ErrorHandler.FILE_EXCEPTION(fileName, fe, usedFiles, format)); throw helper.cancel(new ERR(), fe, "import-file-exception", "filename", fileName); } catch (Cancel c) { throw c; } catch (Throwable t) { notifyObservers( new ErrorHandler.INTERNAL_EXCEPTION( fileName, new RuntimeException(t), usedFiles, format)); throw helper.cancel(new ERR(), t, "import-request-failure"); } finally { try { long size = logPath.size(); store.updateFileSize(logFile, size); } catch (Throwable t) { throw helper.cancel(new ERR(), t, "update-log-file-size"); } MDC.clear(); } }
public void loginProcess() { MDC.put("reqId", ECTUtils.generateToken()); logger.info("loginProcess!!"); logger.info("userName : {} , passWord : {}", userName, "********"); if (!validateLongin()) { addError("loggin fial!!"); return; } /** * Authen Login */ try { String nPassWord = ECTUtils.encrypt(passWord); loginUser = getAuthenDao().loginUser(userName, nPassWord); } catch (Exception ex) { logger.error("Cannot Authen : ", ex); return; } if (loginUser == null) { addError(MessageUtils.getResourceBundleString("login.authen.fail")); logger.warn("Login {} fail!!", loginUser); return; } if (!loginUser.getIsActive()) { addError(MessageUtils.getResourceBundleString("login.authen.disabled")); logger.warn("Login {} block user was disbled!!", loginUser); return; } loggedIn = true; super.getRequest().getSession().setAttribute("userAuthen", loginUser); addInfo(MessageUtils.getResourceBundleString("login.loginprocess")); String path = JsfUtil.getContextPath(); logger.trace("path : {}", path); executeJavaScript( "setTimeout(function(){window.location='" + path + "/pages/form/index.xhtml?firstLogin=true';blockUI.show();},100);"); }
/** * Initialize the logger. * * @param state Source state */ private void initLogger(SourceState state) { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(StringUtils.stripToEmpty(state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_SCHEMA))); sb.append("_"); sb.append(StringUtils.stripToEmpty(state.getProp(ConfigurationKeys.SOURCE_ENTITY))); sb.append("]"); MDC.put("sourceInfo", sb.toString()); }
@Test public void testConvertWithOneEntry() { String k = "MDCConverterTest_k" + diff; String v = "MDCConverterTest_v" + diff; MDC.put(k, v); ILoggingEvent le = createLoggingEvent(); String result = converter.convert(le); assertEquals(k + "=" + v, result); }
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { MDC.put("channel", String.format("[id: 0x%08x]", ctx.channel().hashCode())); if (evt instanceof IdleStateEvent) { LOGGER.error( "Idle connection ({}). PDUs received: {}", ctx.channel().remoteAddress(), this.amountOfResponsesReceived); } super.userEventTriggered(ctx, evt); }
/** * Test endpoint to generate an unexpected exception. Used to confirm that unexpected exceptions * are mapped to WebAPIException types and handled gracefully. * * @return * @throws Exception */ @GET @Path("/unhandledexception") @Produces(MediaType.TEXT_PLAIN) public String getUnhandledException() throws Exception { MDC.put( "getUnhandledException.someSetting", "Fake context specific data that should be logged automatically."); m_logger.debug("Throwing InterruptedException for test purposes."); // any type of exception will do, as long as it is not a WebAPIException. throw new InterruptedException("Something bad happened."); }
/** {@inheritDoc} */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { MDC.put(Version.MDC_ATTRIBUTE, Version.getVersion()); MDC.put(CLIENT_ADDRESS_MDC_ATTRIBUTE, request.getRemoteAddr()); MDC.put(SERVER_ADDRESS_MDC_ATTRIBUTE, request.getServerName()); MDC.put(SERVER_PORT_MDC_ATTRIBUTE, Integer.toString(request.getServerPort())); if (request instanceof HttpServletRequest) { final HttpSession session = ((HttpServletRequest) request).getSession(); if (session != null) { MDC.put(JSESSIONID_MDC_ATTRIBUTE, session.getId()); } } chain.doFilter(request, response); } finally { MDC.clear(); } }
/** * Test endpoint to generate an AMServerProtocolException with a message. * * @return * @throws Exception */ @GET @Path("/amserverprotocolexception1") @Produces(MediaType.TEXT_PLAIN) public String getAMServerProtocolException1() throws Exception { MDC.put( "getAMServerProtocolException1.someSetting", "Fake context specific data that should be logged automatically."); m_logger.debug("Throwing AMServerProtocolException for test purposes."); // Note that in this case there is no error code and no context data. throw new AMServerProtocolException( "Uploading the content failed.", "myserver:myport", "Could not find file."); }
@BeforeSuite public void initSuiteMap(ITestContext testContext) throws Exception { String suiteName = testContext.getSuite().getName(); MDC.put("suite", suiteName); // Workaround of https://jira.spring.io/browse/SPR-4072 springTestContextBeforeTestClass(); springTestContextPrepareTestInstance(); suiteContext.putItContext(suiteName, new IntegrationTestContext()); itContext = suiteContext.getItContext(suiteName); }
public void done(boolean doneSync) { try { if (!doneSync) { // when done asynchronously then restore information from previous thread if (breadcrumbId != null) { MDC.put(MDC_BREADCRUMB_ID, breadcrumbId); } if (exchangeId != null) { MDC.put(MDC_EXCHANGE_ID, exchangeId); } if (messageId != null) { MDC.put(MDC_MESSAGE_ID, messageId); } if (correlationId != null) { MDC.put(MDC_CORRELATION_ID, correlationId); } if (camelContextId != null) { MDC.put(MDC_CAMEL_CONTEXT_ID, camelContextId); } } // need to setup the routeId finally if (routeId != null) { MDC.put(MDC_ROUTE_ID, routeId); } } finally { // muse ensure delegate is invoked delegate.done(doneSync); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf ucpPacket) throws Exception { MDC.put("channel", String.format("[id: 0x%08x]", ctx.channel().hashCode())); this.amountOfResponsesReceived++; if (this.amountOfResponsesReceived == this.amountOfMessages) { // each packet has had its response LOGGER.info("Each packet sent has had its response, closing channel"); numberOfResultsReceived.incrementAndGet(); ctx.close(); } }
// TODO MISSING JAVADOC @AroundInvoke public Object call(final InvocationContext invocationContext) throws Exception { final String id = MDC.get(TRANSACTION_ID); if (id != null) { return invocationContext.proceed(); } MDC.put(TRANSACTION_ID, Long.toHexString(RANDOM.nextLong())); try { return invocationContext.proceed(); } finally { MDC.remove(TRANSACTION_ID); } }
@Override public <R, E extends Throwable> R doRetryable( final IRetryableTask<R, E> task, final IRetryStrategy strategy) throws RetryerException, InterruptedException { checkArgument(task != null, "task can't be null"); checkArgument(strategy != null, "strategy can't be null"); int tryNo = 0; final List<Throwable> reasons = Lists.newArrayList(); MDC.put("task", task.toString()); try { while (true) { try { log.debug("try #{}...", tryNo); if (Thread.interrupted()) { throw new InterruptedException("Interrupted on " + tryNo + " try"); } return task.execute(tryNo); } catch (InterruptedException e) { log.debug("try #{} interrupted: {}", tryNo, e.getMessage()); throw e; } catch (final Throwable reason) { log.debug("try #{} failed: {}", tryNo, reason.getMessage()); reasons.add(reason); // cleanup if (task.isFatalReason(tryNo, reason)) { throw new RetryerException(reasons); } final RetryInfo retryInfo = strategy.shouldRetry(tryNo, reason); if (retryInfo.shouldFail()) { throw new RetryerException(reasons); } else { final long delay = retryInfo.delay(); if (delay > 0) { log.debug("retry after {} ms", delay); Thread.sleep(delay); } else { log.debug("retry now"); } } } finally { tryNo++; } } } finally { MDC.remove("task"); } }
public void begin(int transactionTimeout) { TransactionID txId = currentTransactionIdThreadLocal.get(); if (txId != null) { throw new TransactionException("transaction already started"); } TransactionContext newTx = new TransactionContext(transactionTimeout, transactionIDFactory.createTransactionID()); contextMap.put(newTx.getTransactionId(), newTx); currentTransactionIdThreadLocal.set(newTx.getTransactionId()); MDC.put(MDC_KEY, newTx.getTransactionId().toString()); LOG.debug("begun transaction {}", newTx.getTransactionId()); }
@Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String sessionId = ((HttpServletRequest) servletRequest).getSession().getId(); String url = ((HttpServletRequest) servletRequest).getRequestURI(); String httpMethod = ((HttpServletRequest) servletRequest).getMethod(); String ip = servletRequest.getRemoteAddr(); try { MDC.put(SESSION_ID, sessionId); MDC.put(URL, url); MDC.put(HTTP_METHOD, httpMethod); MDC.put(IP, ip); Logger.info("one request started before filter"); filterChain.doFilter(servletRequest, servletResponse); Logger.info("one request finished after filter"); } finally { MDC.remove(SESSION_ID); MDC.remove(URL); MDC.remove(HTTP_METHOD); MDC.remove(IP); } }
/** * Test endpoint to generate a BadRequestException with status code, message, errorDescription and * some context key value pairs. * * @return * @throws Exception */ @GET @Path("/badrequestexception") @Produces(MediaType.TEXT_PLAIN) public String getBadRequestException() throws Exception { MDC.put( "getBadRequestException.someSetting", "Fake context specific data that should be logged automatically."); m_logger.debug("Throwing getBadRequestException for test purposes."); // Note that in this case there is no error code and no context data. throw new BadRequestException( "PARAMETER_DEVICEID_MISSING", null, ResourceUtilities.DEFAULT_LOCALE, ResourceUtilities.NON_LOCALIZABLE_BASE); }
/** * Test endpoint to generate a BadRequestException with status code, message, errorDescription and * some context key value pairs. * * @return * @throws Exception */ @GET @Path("/internalservererrorexception") @Produces(MediaType.TEXT_PLAIN) public String getInternalServerErrorException() throws Exception { MDC.put( "getInternalServerErrorException.someSetting", "Fake context specific data that should be logged automatically."); m_logger.debug("Throwing InternalServerErrorException for test purposes."); // Note that in this case there is no error code and no context data. throw new InternalServerErrorException( "THIS_IS_INTERNAL_ERROR", "SETTING_INI_XYZ_NOT_CONFIGURED", null, ResourceUtilities.DEFAULT_LOCALE, ResourceUtilities.NON_LOCALIZABLE_BASE); }
@Override public IUndecorator decorate() throws Exception { final String originValue = MDC.get(m_mdcKey); MDC.put(m_mdcKey, m_mdcValueProvider.value()); // Restore origin value upon completion of the command. return new IUndecorator() { @Override public void undecorate(final Throwable throwable) { if (originValue != null) { MDC.put(m_mdcKey, originValue); } else { MDC.remove(m_mdcKey); } } }; }
@Test public void LBCLASSIC_104() throws Exception { buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS); smtpAppender.setAsynchronousSending(false); smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN)); smtpAppender.start(); logger.addAppender(smtpAppender); MDC.put("key", "val"); logger.debug("hello"); MDC.clear(); logger.error("an error", new Exception("an exception")); MimeMultipart mp = verify(smtpServer, TEST_SUBJECT); String body = GreenMailUtil.getBody(mp.getBodyPart(0)); assertTrue("missing HEADER in body", body.startsWith(HEADER.trim())); assertTrue("missing MDC in body", body.contains("key=val")); assertTrue("missing FOOTER in body", body.endsWith(FOOTER.trim())); }