当前位置: 首页>>代码示例>>Java>>正文


Java MDC.put方法代码示例

本文整理汇总了Java中org.apache.log4j.MDC.put方法的典型用法代码示例。如果您正苦于以下问题:Java MDC.put方法的具体用法?Java MDC.put怎么用?Java MDC.put使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.log4j.MDC的用法示例。


在下文中一共展示了MDC.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: login

import org.apache.log4j.MDC; //导入方法依赖的package包/类
/**
 * 登录
 *
 * @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";
    }
}
 
开发者ID:ZHENFENG13,项目名称:ssm-demo,代码行数:29,代码来源:UserController.java

示例2: testMDC

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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);
    }
}
 
开发者ID:symphoniacloud,项目名称:lambda-monitoring,代码行数:17,代码来源:DefaultConsoleAppenderTest.java

示例3: multipleDomains1

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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"));

}
 
开发者ID:skjolber,项目名称:json-log-domain,代码行数:26,代码来源:LoggingTest.java

示例4: testMDC

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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");
}
 
开发者ID:kdgregory,项目名称:log4j-aws-appenders,代码行数:20,代码来源:TestJsonLayout.java

示例5: decide

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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);
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:19,代码来源:MDCFilterTest.java

示例6: unsetLoggingContext

import org.apache.log4j.MDC; //导入方法依赖的package包/类
/**
 * 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());
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:21,代码来源:LoggingService.java

示例7: unsetLoggingContext

import org.apache.log4j.MDC; //导入方法依赖的package包/类
/** 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());
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:22,代码来源:LoggingService.java

示例8: testContextInfo

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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();
}
 
开发者ID:cscfa,项目名称:bartleby,代码行数:24,代码来源:DBAppenderH2Test.java

示例9: visit

import org.apache.log4j.MDC; //导入方法依赖的package包/类
/**
 * 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");
		}
	}
}
 
开发者ID:arianne,项目名称:marauroa,代码行数:26,代码来源:RPScheduler.java

示例10: testMDC

import org.apache.log4j.MDC; //导入方法依赖的package包/类
/**
 * 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"));
}
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:26,代码来源:XMLLayoutTestCase.java

示例11: testMDCEscaped

import org.apache.log4j.MDC; //导入方法依赖的package包/类
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"));
}
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:21,代码来源:XMLLayoutTestCase.java

示例12: indexDocument

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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");
    }
}
 
开发者ID:kuali,项目名称:kc-rice,代码行数:25,代码来源:DocumentAttributeIndexingQueueImpl.java

示例13: doFilter

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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);
	}
}
 
开发者ID:openwide-java,项目名称:owsi-core-parent,代码行数:20,代码来源:Log4jUrlFilter.java

示例14: append

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@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);
}
 
开发者ID:skarpushin,项目名称:summerb,代码行数:21,代码来源:RollingFileAppenderRecurringExcSkip.java

示例15: getRestaurant

import org.apache.log4j.MDC; //导入方法依赖的package包/类
@RequestMapping("/restaurants/{restaurant-id}")
@HystrixCommand(fallbackMethod = "defaultRestaurant")
public ResponseEntity<Restaurant> getRestaurant(
        @PathVariable("restaurant-id") int restaurantId) {
    MDC.put("restaurantId", restaurantId);
    String url = "http://restaurant-service/v1/restaurants/" + restaurantId;
    LOG.debug("GetRestaurant from URL: {}", url);

    ResponseEntity<Restaurant> result = restTemplate.getForEntity(url, Restaurant.class);
    LOG.info("GetRestaurant http-status: {}", result.getStatusCode());
    LOG.debug("GetRestaurant body: {}", result.getBody());

    return new ResponseEntity<>(result.getBody(), HttpStatus.OK);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Microservices-with-Java-9-Second-Edition,代码行数:15,代码来源:RestaurantServiceAPI.java


注:本文中的org.apache.log4j.MDC.put方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。