本文整理汇总了Java中org.apache.log4j.MDC类的典型用法代码示例。如果您正苦于以下问题:Java MDC类的具体用法?Java MDC怎么用?Java MDC使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MDC类属于org.apache.log4j包,在下文中一共展示了MDC类的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: doFilter
import org.apache.log4j.MDC; //导入依赖的package包/类
@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);
}
示例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: createAuditTransaction
import org.apache.log4j.MDC; //导入依赖的package包/类
/** 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);
}
}
}
示例9: decide
import org.apache.log4j.MDC; //导入依赖的package包/类
/**
* 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;
}
示例10: 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);
}
示例11: doFilterInternal
import org.apache.log4j.MDC; //导入依赖的package包/类
@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);
}
示例12: addTransactionInfo
import org.apache.log4j.MDC; //导入依赖的package包/类
/**
* 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());
}
}
}
示例13: getMdcLong
import org.apache.log4j.MDC; //导入依赖的package包/类
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;
}
示例14: testAutoPopulate
import org.apache.log4j.MDC; //导入依赖的package包/类
@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 ) );
}
示例15: LoadBatchCommand
import org.apache.log4j.MDC; //导入依赖的package包/类
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());
}
}