下面列出了怎么用org.apache.log4j.NDC的API类实例代码及写法,或者点击链接到github查看源代码。
void bubbleSort() {
LOG.info( "Entered the sort method.");
for(int i = intArray.length -1; i >= 0 ; i--) {
NDC.push("i=" + i);
OUTER.debug("in outer loop.");
for(int j = 0; j < i; j++) {
NDC.push("j=" + j);
// It is poor practice to ship code with log staments in tight loops.
// We do it anyway in this example.
INNER.debug( "in inner loop.");
if(intArray[j] > intArray[j+1])
swap(j, j+1);
NDC.pop();
}
NDC.pop();
}
}
/**
* Tests CDATA element within NDC content. See bug 37560.
*/
public void testNDCWithCDATA() throws Exception {
Logger logger = Logger.getLogger("com.example.bar");
Level level = Level.INFO;
String ndcMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
NDC.push(ndcMessage);
LoggingEvent event =
new LoggingEvent(
"com.example.bar", logger, level, "Hello, World", null);
Layout layout = createLayout();
String result = layout.format(event);
NDC.clear();
Element parsedResult = parse(result);
NodeList ndcs = parsedResult.getElementsByTagName("log4j:NDC");
assertEquals(1, ndcs.getLength());
StringBuffer buf = new StringBuffer();
for(Node child = ndcs.item(0).getFirstChild();
child != null;
child = child.getNextSibling()) {
buf.append(child.getNodeValue());
}
assertEquals(ndcMessage, buf.toString());
}
/**
* The pattern on the server side: %5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n
* meaning that we are testing NDC, MDC and localization functionality across
* the wire.
*/
public void test4() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
rootLogger.addAppender(socketAppender);
NDC.push("some");
common("T4", "key4", "MDC-TEST4");
NDC.pop();
delay(1);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT4, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.4"));
}
}
/**
* The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n
*
* This test checks whether server side MDC works.
*/
public void test8() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
rootLogger.addAppender(socketAppender);
NDC.push("some8");
common("T8", "key8", "MDC-TEST8");
NDC.pop();
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT8, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.8"));
}
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
count_++;
String ndcName = getClass().getName();
ndcName = ndcName.substring(ndcName.lastIndexOf('.')+1);
NDC.push(ndcName);
NDC.push("call-" + count_);
logger_.info("begin onService");
try
{
onService(req, resp);
}
catch (Exception exc)
{
lastException = exc;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
finally
{
logger_.info("end onService");
NDC.pop();
NDC.pop();
}
}
private int ndcPush() {
int count = 0;
try {
UserContext user = getUser();
if (user != null) {
NDC.push("uid:" + user.getTrueExternalUserId()); count++;
if (user.getCurrentAuthority() != null) {
NDC.push("role:" + user.getCurrentAuthority().getRole()); count++;
Long sessionId = user.getCurrentAcademicSessionId();
if (sessionId != null) {
NDC.push("sid:" + sessionId); count++;
}
}
}
} catch (Exception e) {}
return count;
}
public void run() {
NDC.push("main");
try {
log.info("starting up daemon");
isStarted = true;
//noinspection InfiniteLoopStatement
while (!ss.isClosed()) {
try {
final Socket socket = ss.accept();
socket.setSoTimeout(60000);
socket.setTcpNoDelay(true);
log.info("received connection, running");
executor.execute(new DaemonWorker(socket));
} catch (IOException e) {
log.warn("server socket error", e);
}
}
} finally {
NDC.pop();
}
}
@Override
public void run() {
try {
final InetAddress remoteAddress = socket.getInetAddress();
NDC.push("DaemonWorker(" + socket.getRemoteSocketAddress() + ")");
try {
internalRun();
} finally {
NDC.pop();
}
} catch (RuntimeException e) {
if (e.getCause() instanceof SocketException) {
log.warn("worker exception", e);
} else if (e instanceof IllegalArgumentException) {
log.warn("worker exception", e);
} else {
log.error("worker exception", e);
}
throw e;
}
}
protected void notify(JobExecutionContext jobExecutionContext, String jobStatus) {
try {
StringBuilder mailMessageSubject = new StringBuilder(jobExecutionContext.getJobDetail().getGroup()).append(": ").append(jobExecutionContext.getJobDetail().getName());
MailMessage mailMessage = new MailMessage();
mailMessage.setFromAddress(mailService.getBatchMailingList());
if (jobExecutionContext.getMergedJobDataMap().containsKey(REQUESTOR_EMAIL_ADDRESS_KEY) && !StringUtils.isBlank(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY))) {
mailMessage.addToAddress(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY));
}
if (SchedulerService.FAILED_JOB_STATUS_CODE.equals(jobStatus) || SchedulerService.CANCELLED_JOB_STATUS_CODE.equals(jobStatus)) {
mailMessage.addToAddress(mailService.getBatchMailingList());
}
mailMessageSubject.append(": ").append(jobStatus);
String messageText = MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.MESSAGE_BATCH_FILE_LOG_EMAIL_BODY), getLogFileName(NDC.peek()));
mailMessage.setMessage(messageText);
if (mailMessage.getToAddresses().size() > 0) {
mailMessage.setSubject(mailMessageSubject.toString());
mailService.sendMessage(mailMessage);
}
}
catch (Exception iae) {
LOG.error("Caught exception while trying to send job completion notification e-mail for " + jobExecutionContext.getJobDetail().getName(), iae);
}
}
protected static CallContext register(User callingUser, Account callingAccount, Long userId, Long accountId, String contextId) {
/*
Unit tests will have multiple times of setup/tear-down call to this, remove assertions to all unit test to run
assert s_currentContext.get() == null : "There's a context already so what does this new register context mean? " + s_currentContext.get().toString();
if (s_currentContext.get() != null) { // FIXME: This should be removed soon. I added this check only to surface all the places that have this problem.
throw new CloudRuntimeException("There's a context already so what does this new register context mean? " + s_currentContext.get().toString());
}
*/
CallContext callingContext = null;
if (userId == null || accountId == null) {
callingContext = new CallContext(callingUser, callingAccount, contextId);
} else {
callingContext = new CallContext(userId, accountId, contextId);
}
s_currentContext.set(callingContext);
NDC.push("ctx-" + UuidUtils.first(contextId));
if (s_logger.isTraceEnabled()) {
s_logger.trace("Registered: " + callingContext);
}
s_currentContextStack.get().push(callingContext);
return callingContext;
}
@RequestMapping(value = "/ndc/log4j", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
NDC.push("tx.id=" + investment.getTransactionId());
NDC.push("tx.owner=" + investment.getOwner());
try {
log4jBusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
NDC.pop();
// take out transactionId from the NDC stack
NDC.pop();
NDC.remove();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
public String getValue(LogMessageField field) {
switch (field.getNamedLogField()) {
case Severity:
return loggingEvent.getLevel().toString();
case ThreadName:
return loggingEvent.getThreadName();
case SourceClassName:
return getSourceClassName();
case SourceLineNumber:
return getSourceLineNumber();
case SourceMethodName:
return getSourceMethodName();
case SourceSimpleClassName:
String sourceClassName = getSourceClassName();
if (sourceClassName == null) {
return null;
}
return GelfUtil.getSimpleClassName(sourceClassName);
case LoggerName:
return loggingEvent.getLoggerName();
case NDC:
String ndc = NDC.get();
if (ndc != null && !"".equals(ndc)) {
return ndc;
}
return null;
}
throw new UnsupportedOperationException("Cannot provide value for " + field);
}
/**
* Removes the log message from the Log4J NDC after the request is processed.
*/
@Override
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Removes the log message from the Log4J NDC when the processing thread is
* exited after the start of asynchronous request handling.
*/
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Logs the before-request message through Log4J and
* adds a message the Log4J NDC before the request is processed.
*/
@Override
protected void beforeRequest(HttpServletRequest request, String message) {
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
NDC.push(getNestedDiagnosticContextMessage(request));
}
/**
* Removes the log message from the Log4J NDC after the request is processed
* and logs the after-request message through Log4J.
*/
@Override
protected void afterRequest(HttpServletRequest request, String message) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
}
/**
* Removes the log message from the Log4J NDC after the request is processed.
*/
@Override
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Removes the log message from the Log4J NDC when the processing thread is
* exited after the start of asynchronous request handling.
*/
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Logs the before-request message through Log4J and
* adds a message the Log4J NDC before the request is processed.
*/
@Override
protected void beforeRequest(HttpServletRequest request, String message) {
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
NDC.push(getNestedDiagnosticContextMessage(request));
}
/**
* Removes the log message from the Log4J NDC after the request is processed
* and logs the after-request message through Log4J.
*/
@Override
protected void afterRequest(HttpServletRequest request, String message) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
}
public static void main(String[] args) {
BasicConfigurator.configure();
NDC.push("Client #45890");
logger.info("Awake awake. Put on thy strength.");
Trivial.foo();
InnerTrivial.foo();
logger.info("Exiting Trivial.");
}
public static void main(String[] args) throws IOException {
// Configure the LF5Appender using the DefaultLF5Configurator. This
// will add the LF5Appender to the root of the Category tree.
DefaultLF5Configurator.configure();
// Add an NDC to demonstrate how NDC information is output.
NDC.push("#23856");
// Log some information.
for (int i = 0; i < 10; i++) {
logger.debug("Hello, my name is Homer Simpson.");
logger.info("Mmmmmm .... Chocolate.");
logger.warn("Mmm...forbidden donut.");
}
// Clean up NDC
NDC.pop();
NDC.remove();
NDC.push("Another NDC");
// Log some information.
logger.fatal("Hello, my name is Bart Simpson.");
logger.error("Hi diddly ho good neighbour.");
// Clean up NDC
NDC.pop();
NDC.remove();
// Call methods on both classes.
InitUsingDefaultConfigurator.foo();
InnerInitUsingDefaultConfigurator.foo();
logger.info("Exiting InitUsingDefaultConfigurator.");
}
public static void foo() {
logger.debug("Entered foo in InitUsingDefaultConfigurator class");
NDC.push("#123456");
logger.debug("Hello, my name is Marge Simpson.");
logger.info("D'oh!! A deer! A female deer.");
// Clean up NDC
NDC.pop();
NDC.remove();
}
/**
* Serialize a logging event with ndc.
* @throws Exception if exception during test.
*
*/
public void testSerializationNDC() throws Exception {
Logger root = Logger.getRootLogger();
NDC.push("ndc test");
LoggingEvent event =
new LoggingEvent(
root.getClass().getName(), root, Level.INFO, "Hello, world.", null);
// event.prepareForDeferredProcessing();
int[] skip = new int[] { 352, 353, 354, 355, 356 };
SerializationTestHelper.assertSerializationEquals(
"witness/serialization/ndc.bin", event, skip, 237);
}
/**
* Clear MDC and NDC before test.
*/
public void setUp() {
NDC.clear();
if (MDC.getContext() != null) {
MDC.getContext().clear();
}
}
/**
* The pattern on the server side: %5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n
*
* The test case uses wraps an AsyncAppender around the
* SocketAppender. This tests was written specifically for bug
* report #9155.
* Prior to the bug fix the output on the server did not contain the
* MDC-TEST5 string because the MDC clone operation (in getMDCCopy
* method) operation is performed twice, once from the main thread
* which is correct, and a second time from the AsyncAppender's
* dispatch thread which is incrorrect.
*/
public void test5() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
AsyncAppender asyncAppender = new AsyncAppender();
asyncAppender.setLocationInfo(true);
asyncAppender.addAppender(socketAppender);
rootLogger.addAppender(asyncAppender);
NDC.push("some5");
common("T5", "key5", "MDC-TEST5");
NDC.pop();
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT5, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.5"));
}
}
/**
* The pattern on the server side: %5p %x %X{hostID}${key6} [%t] %c{1} - %m%n
*
* This test checks whether client-side MDC overrides the server side.
* It uses an AsyncAppender encapsulating a SocketAppender
*/
public void test6() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
AsyncAppender asyncAppender = new AsyncAppender();
asyncAppender.setLocationInfo(true);
asyncAppender.addAppender(socketAppender);
rootLogger.addAppender(asyncAppender);
NDC.push("some6");
MDC.put("hostID", "client-test6");
common("T6", "key6", "MDC-TEST6");
NDC.pop();
MDC.remove("hostID");
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT6, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.6"));
}
}
/**
* The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n
*
* This test checks whether client-side MDC overrides the server side.
*/
public void test7() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
rootLogger.addAppender(socketAppender);
NDC.push("some7");
MDC.put("hostID", "client-test7");
common("T7", "key7", "MDC-TEST7");
NDC.pop();
MDC.remove("hostID");
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT7, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.7"));
}
}
static
void common(String dc, String key, Object o) {
String oldThreadName = Thread.currentThread().getName();
Thread.currentThread().setName("main");
int i = -1;
NDC.push(dc);
MDC.put(key, o);
Logger root = Logger.getRootLogger();
logger.setLevel(Level.DEBUG);
rootLogger.setLevel(Level.DEBUG);
logger.log(XLevel.TRACE, "Message " + ++i);
logger.setLevel(Level.TRACE);
rootLogger.setLevel(Level.TRACE);
logger.trace("Message " + ++i);
root.trace("Message " + ++i);
logger.debug("Message " + ++i);
root.debug("Message " + ++i);
logger.info("Message " + ++i);
logger.warn("Message " + ++i);
logger.log(XLevel.LETHAL, "Message " + ++i); //5
Exception e = new Exception("Just testing");
logger.debug("Message " + ++i, e);
root.error("Message " + ++i, e);
NDC.pop();
MDC.remove(key);
Thread.currentThread().setName(oldThreadName);
}
static
void init(String portStr, String configFile) {
try {
port = Integer.parseInt(portStr);
}
catch(java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number ["+ portStr +"].");
}
PropertyConfigurator.configure(configFile);
NDC.push("Server");
}