01: /*
02: * Copyright 2002-2007 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.context.request;
18:
19: import org.apache.log4j.Logger;
20: import org.apache.log4j.NDC;
21:
22: import org.springframework.ui.ModelMap;
23:
24: /**
25: * Request logging interceptor that adds a request context message to the
26: * Log4J nested diagnostic context (NDC) before the request is processed,
27: * removing it again after the request is processed.
28: *
29: * @author Juergen Hoeller
30: * @since 2.5
31: * @see org.apache.log4j.NDC#push(String)
32: * @see org.apache.log4j.NDC#pop()
33: */
34: public class Log4jNestedDiagnosticContextInterceptor implements
35: WebRequestInterceptor {
36:
37: /** Logger available to subclasses */
38: protected final Logger log4jLogger = Logger.getLogger(getClass());
39:
40: private boolean includeClientInfo = false;
41:
42: /**
43: * Set whether or not the session id and user name should be included
44: * in the log message.
45: */
46: public void setIncludeClientInfo(boolean includeClientInfo) {
47: this .includeClientInfo = includeClientInfo;
48: }
49:
50: /**
51: * Return whether or not the session id and user name should be included
52: * in the log message.
53: */
54: protected boolean isIncludeClientInfo() {
55: return this .includeClientInfo;
56: }
57:
58: /**
59: * Adds a message the Log4J NDC before the request is processed.
60: */
61: public void preHandle(WebRequest request) throws Exception {
62: NDC.push(getNestedDiagnosticContextMessage(request));
63: }
64:
65: /**
66: * Determine the message to be pushed onto the Log4J nested diagnostic context.
67: * <p>Default is the request object's <code>getDescription</code> result.
68: * @param request current HTTP request
69: * @return the message to be pushed onto the Log4J NDC
70: * @see WebRequest#getDescription
71: * @see #isIncludeClientInfo()
72: */
73: protected String getNestedDiagnosticContextMessage(
74: WebRequest request) {
75: return request.getDescription(isIncludeClientInfo());
76: }
77:
78: public void postHandle(WebRequest request, ModelMap model)
79: throws Exception {
80: }
81:
82: /**
83: * Removes the log message from the Log4J NDC after the request is processed.
84: */
85: public void afterCompletion(WebRequest request, Exception ex)
86: throws Exception {
87: NDC.pop();
88: }
89:
90: }
|