本文整理汇总了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";
}
}
示例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);
}
}
示例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"));
}
示例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");
}
示例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);
}
示例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());
}
示例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());
}
示例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();
}
示例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");
}
}
}
示例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"));
}
示例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"));
}
示例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");
}
}
示例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);
}
}
示例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);
}
示例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