1 | // Copyright 2004-2007 Jean-Francois Poilpret |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package net.sourceforge.hiveutils.web.logging; |
16 | |
17 | import java.io.IOException; |
18 | |
19 | import javax.servlet.Filter; |
20 | import javax.servlet.FilterChain; |
21 | import javax.servlet.FilterConfig; |
22 | import javax.servlet.ServletException; |
23 | import javax.servlet.ServletRequest; |
24 | import javax.servlet.ServletResponse; |
25 | import javax.servlet.http.HttpServletRequest; |
26 | |
27 | import org.apache.log4j.NDC; |
28 | |
29 | /** |
30 | * Filter that will add a Diagnostic Context (NDC) to the current stack of NDC |
31 | * of log4j. This can be used for any purpose. |
32 | * This default implementation pushes no NDC at all but can be overridden to |
33 | * push any context. |
34 | * |
35 | * @author Jean-Francois Poilpret |
36 | */ |
37 | public class LoggingContextInitFilter implements Filter |
38 | { |
39 | public void init(FilterConfig filterConfig) |
40 | { |
41 | } |
42 | |
43 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) |
44 | throws IOException, ServletException |
45 | { |
46 | String context = getContext((HttpServletRequest) req); |
47 | if (context != null) |
48 | { |
49 | NDC.push(context); |
50 | } |
51 | try |
52 | { |
53 | chain.doFilter(req, res); |
54 | } |
55 | finally |
56 | { |
57 | if (context != null) |
58 | { |
59 | NDC.remove(); |
60 | } |
61 | } |
62 | } |
63 | |
64 | /** |
65 | * Returns the context to be pushed on the NDC stack. |
66 | * This context must be extracted from the current request. |
67 | * <p> |
68 | * By default, this method returns <code>null</code> (ie, no context pushed) |
69 | * but you would override it to push whatever is suitable (eg, the name of |
70 | * the user who sent the current request). |
71 | * @param req the current http request |
72 | * @return the context to be pushed on the NDC stack |
73 | */ |
74 | protected String getContext(HttpServletRequest req) |
75 | { |
76 | return null; |
77 | } |
78 | |
79 | public void destroy() |
80 | { |
81 | } |
82 | } |