@Test public void mdc() throws EvaluationException { MDC.put("key", "val"); LoggingEvent event = makeEvent("x"); doEvaluateAndCheck("e.mdc['key'] == 'val'", event, true); MDC.clear(); }
@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())); }
@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); } } }
/** * 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); } }
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(); } }
@AfterClass protected void tearDownClass() { MDC.remove("id"); MDC.remove("test"); LOG.info("===[ {} ]==============================[END ]===", clasz.getSimpleName()); MDC.remove("test-class"); }
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); }
// 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"); } }
/** @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 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); } } }
/** @see wicket.RequestCycle#onEndRequest() */ @SuppressWarnings("nls") @Override protected void onEndRequest() { J2DBGlobals.setServiceProvider(null); WebClientSession webClientSession = (WebClientSession) getSession(); WebClient webClient = webClientSession.getWebClient(); if (webClient != null) { try { webClient.onEndRequest(webClientSession); } finally { MDC.remove("clientid"); MDC.remove("solution"); } } }
/** Execute the given runnable within the context of this CDC. */ public void execute(Runnable r) { String session = MDC.get(MDC_SESSION); String cell = MDC.get(MDC_CELL); String domain = MDC.get(MDC_DOMAIN); NDC ndc = NDC.cloneNdc(); try { apply(); r.run(); } finally { setMdc(MDC_DOMAIN, domain); setMdc(MDC_CELL, cell); setMdc(MDC_SESSION, session); NDC.set(ndc); } }
@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(); } }
@After public void tearDown() throws Exception { lc = null; converter.stop(); converter = null; MDC.clear(); }
@Before public void setUp() throws Exception { lc = new LoggerContext(); converter = new MDCConverter(); converter.start(); MDC.clear(); }
private List<Loggable> createCallAwareLoggables() { List<Loggable> loggables = Lists.newArrayList(); loggables.add( createLoggable(WebKeys.CALL_IDENTIFIER, MDC.get(WebKeys.MDC_KEY_CALL_IDENTIFIER))); return loggables; }
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);"); }
/** * Setup the cell diagnostic context of the calling thread. Threads created from the calling * thread automatically inherit this information. The old diagnostic context is captured and * returned. */ public static CDC reset(String cellName, String domainName) { CDC cdc = new CDC(); setMdc(MDC_CELL, cellName); setMdc(MDC_DOMAIN, domainName); MDC.remove(MDC_SESSION); NDC.clear(); return cdc; }
private void appendMDC(StringBuilder sb) { if (!StringUtils.isEmpty(MDC.get(NODE_NAME_PROP))) { sb.append(" n:").append(MDC.get(NODE_NAME_PROP)); } if (!StringUtils.isEmpty(MDC.get(COLLECTION_PROP))) { sb.append(" c:").append(MDC.get(COLLECTION_PROP)); } if (!StringUtils.isEmpty(MDC.get(SHARD_ID_PROP))) { sb.append(" s:").append(MDC.get(SHARD_ID_PROP)); } if (!StringUtils.isEmpty(MDC.get(REPLICA_PROP))) { sb.append(" r:").append(MDC.get(REPLICA_PROP)); } if (!StringUtils.isEmpty(MDC.get(CORE_NAME_PROP))) { sb.append(" x:").append(MDC.get(CORE_NAME_PROP)); } }
public String toString() { String boardFormat = MDC.get("board_format"); if (boardFormat != null && boardFormat.equals("simple")) { return simpleString(); } else { return jsonString(); } }
@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); } } }; }
/** * 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 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())); }
/** * {@inheritDoc} * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; String transaction = httpRequest.getHeader(headerName); if (transaction == null || transaction.length() == 0) { transaction = ANONYMOUS; } MDC.put(mdcKey, transaction); try { chain.doFilter(request, response); } finally { MDC.remove(mdcKey); } }
/** * {@inheritDoc} * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; String username = ANONYMOUS; Principal principal = httpRequest.getUserPrincipal(); if (principal != null && principal.getName().length() > 0) { username = principal.getName(); } MDC.put(mdcKey, username); try { chain.doFilter(request, response); } finally { MDC.remove(mdcKey); } }
/* * (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain) */ @Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { try { final SecurityContext context = SecurityContextHolder.getContext(); String uid = null; if (context != null) { final Authentication authentication = context.getAuthentication(); if (authentication != null) { uid = context.getAuthentication().getName(); } } MDC.put(identifiert, uid == null ? NOT_KNOWN : uid); chain.doFilter(request, response); } finally { MDC.remove(identifiert); } }
@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); }