01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.web.filter;
18:
19: import javax.servlet.http.HttpServletRequest;
20:
21: import org.apache.log4j.Logger;
22: import org.apache.log4j.NDC;
23:
24: /**
25: * Request logging filter that adds the request log message to the Log4J
26: * nested diagnostic context (NDC) before the request is processed,
27: * removing it again after the request is processed.
28: *
29: * @author Rob Harrop
30: * @author Juergen Hoeller
31: * @since 1.2.5
32: * @see #setIncludeQueryString
33: * @see #setBeforeMessagePrefix
34: * @see #setBeforeMessageSuffix
35: * @see #setAfterMessagePrefix
36: * @see #setAfterMessageSuffix
37: * @see org.apache.log4j.NDC#push(String)
38: * @see org.apache.log4j.NDC#pop()
39: */
40: public class Log4jNestedDiagnosticContextFilter extends
41: AbstractRequestLoggingFilter {
42:
43: /** Logger available to subclasses */
44: protected final Logger log4jLogger = Logger.getLogger(getClass());
45:
46: /**
47: * Logs the before-request message through Log4J and
48: * adds a message the Log4J NDC before the request is processed.
49: */
50: protected void beforeRequest(HttpServletRequest request,
51: String message) {
52: if (log4jLogger.isDebugEnabled()) {
53: log4jLogger.debug(message);
54: }
55: NDC.push(getNestedDiagnosticContextMessage(request));
56: }
57:
58: /**
59: * Determine the message to be pushed onto the Log4J nested diagnostic context.
60: * <p>Default is a plain request log message without prefix or suffix.
61: * @param request current HTTP request
62: * @return the message to be pushed onto the Log4J NDC
63: * @see #createMessage
64: */
65: protected String getNestedDiagnosticContextMessage(
66: HttpServletRequest request) {
67: return createMessage(request, "", "");
68: }
69:
70: /**
71: * Removes the log message from the Log4J NDC after the request is processed
72: * and logs the after-request message through Log4J.
73: */
74: protected void afterRequest(HttpServletRequest request,
75: String message) {
76: NDC.pop();
77: if (log4jLogger.isDebugEnabled()) {
78: log4jLogger.debug(message);
79: }
80: }
81:
82: }
|