/** * 登录 * * @param user * @param request * @return */ @RequestMapping("/login") public String login(User user, HttpServletRequest request) { try { String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8"); user.setPassword(MD5pwd); } catch (Exception e) { user.setPassword(""); } User resultUser = userService.login(user); log.info("request: user/login , user: " + user.toString()); if (resultUser == null) { request.setAttribute("user", user); request.setAttribute("errorMsg", "请认真核对账号、密码!"); return "login"; } else { HttpSession session = request.getSession(); session.setAttribute("currentUser", resultUser); MDC.put("userName", user.getUserName()); return "redirect:/main.jsp"; } }
@Test public void testMDC() { PrintStream original = System.out; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStream, true)); MDC.put("AWSRequestId", "AWS-REQUEST-ID"); Logger logger = LoggerFactory.getLogger("TEST-LOGGER"); logger.info("TEST-MESSAGE"); assertThat(outputStream.toString(), matchesPattern("^\\[[0-9\\-:\\. ]{23}\\] AWS-REQUEST-ID INFO TEST-LOGGER - TEST-MESSAGE\\n$")); } finally { System.setOut(original); } }
@Test public void multipleDomains1() { MDC.put("uname", "magnus"); logger.info(name("java").version(1.7).tags(LanguageTag.JIT, LanguageTag.BYTECODE) .and(host("127.0.0.1").port(8080)) .and(system("fedora").tags(LINUX)), "Hello world"); List<ILoggingEvent> capture = rule.capture(); assertThat(capture.size(), is(1)); assertThat(rule, message("Hello world")); assertThat(rule, qualifier("language").key("name").value("java")); assertThat(rule, qualifier("network").key("host").value("127.0.0.1")); assertThat(rule, key("system").value("fedora")); // multiple tags, from a domain assertThat(rule, qualifier("language").tags(LanguageTag.JIT, LanguageTag.BYTECODE)); // MDC assertThat(rule, mdc("uname", "magnus")); }
@Test public void testMDC() throws Exception { initialize("TestJsonLayout/default.properties"); MDC.put("foo", "bar"); MDC.put("argle", "bargle"); logger.debug(TEST_MESSAGE); MDC.clear(); captureLoggingOutput(); assertCommonElements(TEST_MESSAGE); DomAsserts.assertCount("children of mdc", 2, dom, "/data/mdc/*"); DomAsserts.assertEquals("mdc child 1", "bar", dom, "/data/mdc/foo"); DomAsserts.assertEquals("mdc child 2", "bargle", dom, "/data/mdc/argle"); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; SecurityContext context = (SecurityContext) req.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY); if (context != null) { Authentication authentication = context.getAuthentication(); if (authentication instanceof OAuth2Authentication && authentication.isAuthenticated()) { authentication = ((OAuth2Authentication) authentication).getUserAuthentication(); if (authentication != null) { DiscordUserDetails details = SecurityUtils.getDetails(authentication); if (details != null) { MDC.put("userId", details.getId()); } } } } chain.doFilter(request, response); }
/** * Remove the elements from the Message Driven Context (MDC) of Log4J, that may have been added by the call to setLoggingContext(). */ public static void unsetLoggingContext() { Stack<Map<String, Object>> stack = t_loggingContext.get(); if (stack == null || stack.size() == 0) throw new UnsupportedOperationException("The unsetLoggingContext() method can only be called after a setLoggingContext()"); // Remove the current context if (MDC.getContext() != null) { Set<String> keys = new HashSet<String>(MDC.getContext().keySet()); for (String key : keys) MDC.remove(key); } // Now add the elements of the previous logging context into the MDC Map<String, Object> previousLoggingContext = stack.pop(); for (Map.Entry<String, Object> me : previousLoggingContext.entrySet()) MDC.put(me.getKey(), me.getValue()); }
/** Remove the elements from the Message Driven Context (MDC) of Log4J, that may have been added by the call to setLoggingContext(). * @param payload Any serializable object. * @param messageInfo the corresponding MessageInfo object, as specified in the configuration file. */ public static void unsetLoggingContext(Object payload, MessageInfo messageInfo) { Stack<Map<String, Object>> stack = t_loggingContext.get(); if (stack == null || stack.size() == 0) throw new UnsupportedOperationException("The unsetLoggingContext() method can only be called after a setLoggingContext()"); // Remove the current context if (MDC.getContext() != null) { Set<String> keys = new HashSet<String>(MDC.getContext().keySet()); for (String key : keys) MDC.remove(key); } // Now add the elements of the previous logging context into the MDC Map<String, Object> previousLoggingContext = stack.pop(); for (Map.Entry<String, Object> me : previousLoggingContext.entrySet()) MDC.put(me.getKey(), me.getValue()); }
/** Creates an AuditTransaction instance, if not already created, and adds it to the UOW. */ private void createAuditTransaction() throws ApplicationExceptions, FrameworkException { if (m_transactionId == null) { try { AuditTransaction at = new AuditTransaction(); at.generateKey(); at.setProcessName((String) MDC.get(AuditTransactionMeta.PROCESS_NAME)); at.setSubProcessName((String) MDC.get(AuditTransactionMeta.SUB_PROCESS_NAME)); at.setReason((String) MDC.get(AuditTransactionMeta.REASON)); if (SecurityManager.getPrincipal() != null && SecurityManager.getPrincipal().getName() != null) at.setCreatedBy(SecurityManager.getPrincipal().getName()); at.setCreatedOn(new DateTime()); m_uow.addSpecial(at); m_transactionId = at.getTransactionId(); if (log.isDebugEnabled()) log.debug("Created AuditTransaction: " + at); } catch (ValidationException e) { if (log.isDebugEnabled()) log.debug("Exception thrown during creation of AuditTransaction", e); throw new ApplicationExceptions(e); } } }
/** * Returns Filter#DENY if Expression returns false based on the values * returned from the MDC Context. * * @param event * <code>LoggingEvent</code> */ public int decide(final LoggingEvent event) { int ret = DENY; if (keys != null && expression != null) { final List<Object> mdcValues = new ArrayList<Object>(); final List<Class<String>> keyTypes = new ArrayList<Class<String>>(); final String[] keyValues = keys.split(SPLIT_EXPRESSION); if (keyValues != null) { for (final String keyValue : keyValues) { final Object mdcValue = MDC.get(keyValue); keyTypes.add((Class<String>) keyValue.getClass()); mdcValues.add(mdcValue); } } ret = evaluate(getExpressionEvaluator(keyTypes, keyValues), mdcValues); } return ret; }
@Test public void decide() { assertNotNull(mdcFilter); mdcFilter.setExpression("MessageId!=null || LoggedBy!=null"); mdcFilter.setKeys("LoggedBy,MessageId"); final LoggingEvent event = new LoggingEvent("", LOG, LOG.getLevel(), "MessageId=123", null); MDC.put("LoggedBy", "abc"); MDC.put("fff", "abc"); final int ret = mdcFilter.decide(event); LOG.info("decide: " + ret); assertTrue(ret == Filter.NEUTRAL); }
@Override @SuppressWarnings("checkstyle:linelength") public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { if (origin == null) { LOG.warn("CORS origin has not been set - filter disabled"); } else { String requestOrigin = request.getHeader("Origin"); String responseOrigin = requestOrigin == null ? origin : requestOrigin; response.setHeader("Access-Control-Allow-Origin", responseOrigin); response.setHeader("Access-Control-Allow-Credentials", "true"); // If it's a pre-flight check then provide more information. if (request.getHeader("Access-Control-Request-Method") != null) { response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "Accept, Cache-Control, Content-Type, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With"); } response.setHeader("Access-Control-Max-Age", "3600"); } MDC.put("sessionId", request.getSession() != null ? request.getSession().getId() : ""); chain.doFilter(request, response); }
/** * This API is used for adding trasaction information in logs * * @param cadTransId * @param extTransId * @param userId */ public final void addTransactionInfo(final ScribeCommandObject scribeCommandObject) { if (enabled) { /* If Scribe transaction id is not null */ if (scribeCommandObject.getIntTansId() != null) { /* Add internal transaction id information in MDC */ MDC.put(intTransIdConst, scribeCommandObject.getIntTansId()); } /* If external transaction id is not null */ if (scribeCommandObject.getExtTransId() != null) { /* Add external transaction id information in MDC */ MDC.put(extTransIdConst, scribeCommandObject.getExtTransId()); } } }
long getMdcLong ( String key, long defval ) { final Object o = MDC.get ( key ); if ( o == null ) return defval; if ( o instanceof String ) { try { return new Long ( o.toString () ); } catch ( NumberFormatException x ) { return defval; } } if ( o instanceof Long ) { return (Long)o; } return defval; }
@SuppressWarnings("deprecation") @Test public void testAutoPopulate () { final TestClock tc = new TestClock ( 1234567890123L ); final EcompLayout layout = new EcompLayout (); MDC.put ( EcompFields.kBeginTimestampMs, Long.toString ( SaClock.now () ) ); tc.forward ( 60*1000L ); layout.format ( new LoggingEvent ( "foo.bar", Category.getRoot (), Priority.INFO, "foobar", null ) ); assertEquals ( "2009-02-13T23:31:30.123+00:00", MDC.get ( EcompFields.kBeginTimestamp ) ); assertEquals ( "2009-02-13T23:32:30.123+00:00", MDC.get ( EcompFields.kEndTimestamp ) ); assertEquals ( "60000", MDC.get ( EcompFields.kElapsedTimeMs ) ); }
public LoadBatchCommand( Locus locus, SegmentCacheManager cacheMgr, Dialect dialect, RolapCube cube, List<CellRequest> cellRequests) { this.locus = locus; this.cacheMgr = cacheMgr; this.dialect = dialect; this.cube = cube; this.cellRequests = cellRequests; if (MDC.getContext() != null) { this.mdc.putAll(MDC.getContext()); } }
public void run() { this.setName("Thread_" + i); final String s = "Group_" + i; i++; MDC.put(GroupRollingFileAppender.GROUP_KEY, s); for (int k = 0; k < 10; k++) { logger.info(this.getName() + " " + System.currentTimeMillis(), new Exception("123")); logger.info(s + " " + System.currentTimeMillis() + ":JJJJJJJJJ" + " " + k); } }
public static Logger getLogger(Object o) { /*if (Settings.MODE_DEV && !Logger.getRootLogger().getAllAppenders().hasMoreElements()) initLog4jSimple();*/ if (!LOG4J_OPEN) return nopLogger; Class<?> clazz = o.getClass(); if (o instanceof Class<?>) clazz = (Class<?>) o; Logger logger = loggers.get(clazz); if (logger == null) { logger = Logger.getLogger(clazz); loggers.put(clazz, logger); } Throwable t = new Throwable(); MDC.put("location", t.getStackTrace()[2]); // 出错处的堆栈信息 return logger; }
/** * Tests the format of the MDC portion of the layout to ensure * the key-value pairs we put in turn up in the output file. * @throws Exception */ public void testMDC() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setProperties(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } MDC.put("key1", "val1"); MDC.put("key2", "val2"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter()}); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.1")); }
public void testMDCEscaped() throws Exception { XMLLayout xmlLayout = new XMLLayout(); xmlLayout.setProperties(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } MDC.put("blahAttribute", "<blah value='blah'>"); MDC.put("<blahKey value='blah'/>", "blahValue"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter() }); assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.2")); }
@Test public void testAppendMDC(){ String msg="this is a message"; MDC.put("uuid", "1000"); MDC.put("recordAssociation", "xyz"); String thread=Thread.currentThread().getName(); database.command(new OCommandSQL("delete from "+DB_TABLE_NAME)).execute(); log.error(2); appender.finalize(); List<ODocument> list=database.command(new OCommandSQL("select * from "+DB_TABLE_NAME+" limit 1")).execute(); ODocument result=list.get(0); OTrackedMap map=result.field(EventMapper.PROPERTIES); Assert.assertEquals("1000",map.get("uuid")); Assert.assertEquals("xyz",map.get("recordAssociation")); }
@Override public void indexDocument(String documentId) { if (StringUtils.isBlank(documentId)) { throw new RiceIllegalArgumentException("documentId was null or blank"); } MDC.put("docId", documentId); try { long t1 = System.currentTimeMillis(); LOG.info("Indexing document attributes for document " + documentId); Document document = getWorkflowDocumentService().getDocument(documentId); if (document == null) { throw new RiceIllegalArgumentException("Failed to locate document with the given id: " + documentId); } DocumentContent documentContent = KewApiServiceLocator.getWorkflowDocumentService().getDocumentContent(documentId); List<SearchableAttributeValue> attributes = buildSearchableAttributeValues(document, documentContent); KEWServiceLocator.getRouteHeaderService().updateRouteHeaderSearchValues(documentId, attributes); long t2 = System.currentTimeMillis(); LOG.info("...finished indexing document " + documentId + " for document search, total time = " + (t2 - t1) + " ms."); } finally { MDC.remove("docId"); } }
/** * Get the Log4J MDC threadlocal via reflection * @return the MDC ThreadLocalMap object or null if unset or error */ protected static ThreadLocal getMDCThreadLocal() { try { Field mdcField = MDC.class.getDeclaredField("mdc"); if (mdcField != null) { mdcField.setAccessible(true); Object mdc = mdcField.get(null); Field tlmField = MDC.class.getDeclaredField("tlm"); if (tlmField != null) { tlmField.setAccessible(true); return (ThreadLocal) tlmField.get(mdc); } } } catch (NoSuchFieldException nsfe) { nsfe.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } return null; }
@Test public void testContextInfo() throws SQLException { lc.putProperty("testKey1", "testValue1"); MDC.put("k"+diff, "v"+diff); ILoggingEvent event = createLoggingEvent(); appender.append(event); Statement stmt = connectionSource.getConnection().createStatement(); ResultSet rs = null; rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID = "+ existingRowCount); Map<String, String> map = appender.mergePropertyMaps(event); System.out.println("ma.size="+map.size()); int i = 0; while (rs.next()) { String key = rs.getString(2); assertEquals(map.get(key), rs.getString(3)); i++; } assertTrue(map.size() != 0); assertEquals(map.size(), i); rs.close(); }
@Test public void testContextInfo() throws SQLException { loggerContext.putProperty("testKey1", "testValue1"); MDC.put("k" + diff, "v" + diff); ILoggingEvent event = createLoggingEvent(); appender.append(event); Statement stmt = connectionSource.getConnection().createStatement(); ResultSet rs = null; rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID=1"); Map<String, String> map = appender.mergePropertyMaps(event); int i = 0; while (rs.next()) { String key = rs.getString(2); assertEquals(map.get(key), rs.getString(3)); i++; } assertTrue(map.size() != 0); assertEquals(map.size(), i); rs.close(); stmt.close(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; StringBuilder builder = new StringBuilder(); builder.append(httpRequest.getRequestURI()); if (httpRequest.getQueryString() != null) { builder.append("?"); builder.append(httpRequest.getQueryString()); } MDC.put(LOG4J_URL_FILTER_MAP_KEY, builder.toString()); } try { chain.doFilter(request, response); } finally { MDC.remove(LOG4J_URL_FILTER_MAP_KEY); } }
@Override public void onAction(final Player player, final RPAction action) { if (!action.has(TEXT)) { return; } String username = PlayerEntryContainer.getContainer().get(player).username; // remove "context" because it contains a copy of the action with the error object. // Thus resulting a message with duplicated information that is hard to read Object context = MDC.get("context"); MDC.remove("context"); logger.error(player.getName() + " (" + username + "):" + System.getProperty("line.separator") + action.get(TEXT).replaceAll("\r\n", System.getProperty("line.separator"))); MDC.put("context", context); }
private void handleCaptureStartRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String room = request.getParameter("room"); String seqNum = request.getParameter("sequenceNumber"); String screenInfo = request.getParameter("screenInfo"); String userName = request.getParameter("userName"); String streamName = request.getParameter("streamName"); // get width & height String[] screen = screenInfo.split("x"); // create a dim obj Dimension screenDim = new Dimension(Integer.valueOf(screen[0]), Integer.valueOf(screen[1])); MDC.put("meetingId", room); log.debug("handleCaptureStartRequest - room: {} seq: {} screen: {} userName ", new Object[] { room, seqNum, screenInfo, userName }); MDC.remove("meetingId"); // block dimension and svc2 not passed sessionManager.createSession(room, screenDim, userName, streamName, Integer.valueOf(seqNum)); }
@Override public void append(LoggingEvent le) { if (interruptThread) { super.append(le); return; } String exLocationCode = enqueueLogginEventForAnalysis(le); if (knownExcCodes.contains(exLocationCode)) { return; } if (exLocationCode != null) { MDC.put(MDC_EXC_CODE, "[excCode=" + exLocationCode + "]: "); } else { // it might be there after previous append, ensure to clean up MDC.remove(MDC_EXC_CODE); } super.append(le); MDC.remove(MDC_EXC_CODE); }
/** * This is a test for * <a href="http://jira.pentaho.com/browse/MONDRIAN-994">MONDRIAN-994</a>. * It checks that the MDC logging context is passed through all the * threads. */ public void testMdc() { final TestContext context = udfTestContext( "<UserDefinedFunction name=\"Mdc\" className=\"" + MdcUdf.class.getName() + "\"/>\n"); MDC.put(MDC_KEY, MDC_OBJECT); try { context.executeQuery( "with member [Measures].[MDC] as 'Mdc([Measures].[Unit Sales])' " + "select {[Measures].[MDC]} on columns from [Sales]"); } finally { MDC.remove(MDC_KEY); } }
public static void addKeys(ConsumerBean consumer,String userId,String itemId,String recTag) { if (consumer != null) { if (recTag != null) MDC.put(MDC_CONSUMER_KEY, consumer.getShort_name()+":"+recTag); else MDC.put(MDC_CONSUMER_KEY, consumer.getShort_name()); } else MDC.put(MDC_CONSUMER_KEY, ""); if (userId != null) MDC.put(MDC_USER_KEY, userId); else MDC.put(MDC_USER_KEY, ""); if (itemId != null) MDC.put(MDC_ITEM_KEY, itemId); else MDC.put(MDC_ITEM_KEY, ""); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { DatagramPacket packet = (DatagramPacket) msg; try { InputStream stream = new ByteBufInputStream(packet.content()); Object data = new CompactObjectInputStream(stream, ClassResolvers.cacheDisabled(null)).readObject(); MDC.put("id", LogSourceId.getInstance().getId()); logger.callAppenders(((LoggingEventWrapper) data).event); } catch (Throwable e){ System.out.println(e); } ReferenceCountUtil.release(msg); }
/** * For each action in the actual turn, make it to be run in the * ruleProcessor. * * @param ruleProcessor * the class that really run the action. */ public synchronized void visit(IRPRuleProcessor ruleProcessor) { for (Map.Entry<RPObject, List<RPAction>> entry : actualTurn.entrySet()) { RPObject object = entry.getKey(); List<RPAction> list = entry.getValue(); for (RPAction action : list) { MDC.put("context", object + " " + action); try { if ((DebugInterface.get()).executeAction(object, action)) { ruleProcessor.execute(object, action); } } catch (Exception e) { logger.error("error in visit()", e); } MDC.remove("context"); } } }
/** * processes a command * * @param metaData meta data about the command to process */ private void processCommand(DBCommandMetaData metaData) { MDC.put("context", metaData + " "); if (TransactionPool.get() == null) { logger.warn("Database not initialized, skipping database operation"); return; } for (int i = 0; i < 5; i++) { if (executeDBAction(metaData)) { break; } logger.warn("Retrying DBCommand " + metaData); } if (metaData.getCommand() instanceof DBCommandWithCallback) { DBCommandWithCallback commandWithCallback = (DBCommandWithCallback) metaData.getCommand(); commandWithCallback.invokeCallback(); } if (metaData.isResultAwaited()) { metaData.setProcessedTimestamp(System.currentTimeMillis()); DBCommandQueue.get().addResult(metaData); } MDC.put("context", ""); }
private void downloadFeed(String feedName) { try { MDC.put("feed", feedName); TaxiiStatus.Feed feed = taxiiStatusDao.find(feedName); if (feed == null) { feed = new TaxiiStatus.Feed(); feed.setName(feedName); } boolean more; do { more = pollAndUpdateFeed(feed); taxiiStatusDao.updateOrAdd(feed); } while (more); } catch(Exception e) { statistics.incrementErrors(); LOG.error("Error while processing feed " + feedName, e); return ; } finally { MDC.clear(); } }
private boolean pollAndUpdateFeed(TaxiiStatus.Feed feed) throws Exception { try { String messageId = createMessageId(); MDC.put("messageId", messageId); TaxiiPollResponse response = poll(messageId, feed); if (response.getResultId() != null && response.isMore()) { feed.setMore(response.isMore()); feed.setResultId(response.getResultId()); feed.setResultPartNumber(response.getResultPartNumber()); } else { feed.setMore(null); feed.setResultId(null); feed.setResultPartNumber(null); } feed.setIoErrorCount(null); feed.setLastUpdate(getLastUpdate(response)); return response.isMore(); } catch (IOException e) { handleIOError(feed, e); return false; } }
@Test public void testAppendMDC(){ String msg="this is a message"; MDC.put("uuid", "1000"); MDC.put("recordAssociation", "xyz"); String thread=Thread.currentThread().getName(); appender.getSession().execute("TRUNCATE log.log;"); log.error(2); ResultSet results= appender.getSession().execute("SELECT * from log.log"); List<Row> list=results.all(); if(list!=null && list.size()>0) { Row row=list.get(0); Map<String,String> map=row.getMap(EventMapper.PROPERTIES, String.class, String.class); Assert.assertEquals("1000",map.get("uuid")); Assert.assertEquals("xyz",map.get("recordAssociation")); } else Assert.fail(); }
@Test public void testTenantPropagation() throws Exception { String content = "test"; String tenantId = "tenantId"; handlerConfiguration.verifier = () -> { assertEquals(tenantId, MDC.get(MdcKeys.ACCOUNT_ID)); }; TenancyContext context = new DefaultTenancyContext(); context.setTenant(new DefaultTenant(tenantId, null)); TenancyContextHolder.setContext(context); messagingService.sendMessage(content); MultiTenantApplication.Message message = messagingService.receiveMessage(); assertEquals(content, message.getContent()); assertEquals(tenantId, message.getTenantId()); assertEquals(null, message.getPriority()); assertEquals(null, message.getUserId()); }
@Test public void testSecurityPropagation() throws Exception { String content = "test"; String tenantId = "tenantId"; String user = "user"; handlerConfiguration.verifier = () -> { assertEquals(tenantId, MDC.get(MdcKeys.ACCOUNT_ID)); assertEquals(user, MDC.get(MdcKeys.USER_ID)); }; given().content(content).auth().basic(user, "password").post("/private/{tenant}", tenantId).then().statusCode(200); MultiTenantApplication.Message message = messagingService.receiveMessage(); assertEquals(content, message.getContent()); assertEquals(tenantId, message.getTenantId()); assertEquals(null, message.getPriority()); assertEquals(user, message.getUserId()); }
static public void mdcPut(mdcKeys key, Object value) { LogParameters logParameters = (LogParameters) MDC.get("ContextualParameters"); if (logParameters == null) { throw new IllegalStateException("ContextualParameters is null: call mdcInit() before!"); } logParameters.put(key.toString().toLowerCase(), value); }