KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jresearch > gossip > log > avalon > JGossipLog


1 /*
2  * $$Id: JGossipLog.java,v 1.3 2005/06/07 12:32:33 bel70 Exp $$
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * The contents of this file are subject to the Mozilla Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License
8  * at http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific language governing rights and
13  * limitations under the License.
14  *
15  * The Original Code is JGossip forum code.
16  *
17  * The Initial Developer of the Original Code is the JResearch, Org.
18  * Portions created by the Initial Developer are Copyright (C) 2004
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  * Dmitry Belov <bel@jresearch.org>
23  *
24  * ***** END LICENSE BLOCK ***** */

25 /*
26  * Created on 07.09.2004
27  *
28  */

29 package org.jresearch.gossip.log.avalon;
30
31 import java.io.File JavaDoc;
32 import java.io.PrintWriter JavaDoc;
33 import java.text.SimpleDateFormat JavaDoc;
34 import java.util.Date JavaDoc;
35 import java.util.Properties JavaDoc;
36 import java.util.TimeZone JavaDoc;
37
38 import javax.naming.InitialContext JavaDoc;
39 import javax.servlet.http.HttpSession JavaDoc;
40 import javax.sql.DataSource JavaDoc;
41
42 import org.apache.log.ContextMap;
43 import org.apache.log.Hierarchy;
44 import org.apache.log.LogTarget;
45 import org.apache.log.Logger;
46 import org.apache.log.Priority;
47 import org.apache.log.format.PatternFormatter;
48 import org.apache.log.output.db.DefaultJDBCTarget;
49 import org.apache.log.output.io.WriterTarget;
50 import org.apache.log.output.io.rotate.RotateStrategyByDate;
51 import org.apache.log.output.io.rotate.RotatingFileTarget;
52 import org.apache.log.output.io.rotate.UniqueFileStrategy;
53 import org.jresearch.gossip.IConst;
54 import org.jresearch.gossip.beans.user.User;
55 import org.jresearch.gossip.exception.SystemException;
56 import org.jresearch.gossip.log.LogLevel;
57
58 /**
59  * @author dbelov
60  *
61  */

62 public class JGossipLog {
63
64     public static final Priority[] PRIORITIES = new Priority[] { Priority.INFO,
65             Priority.WARN, Priority.ERROR, Priority.FATAL_ERROR, Priority.DEBUG };
66
67     private Logger appLogger;
68
69     private Logger auditLogger;
70
71     private static SimpleDateFormat JavaDoc dateFormat;
72
73     private static JGossipLog instance;
74
75     private static Object JavaDoc lock = new Object JavaDoc();
76
77     public synchronized static JGossipLog getInstance() throws SystemException {
78
79         if (instance == null) {
80             synchronized (lock) {
81                 if (instance == null) {
82                     instance = new JGossipLog();
83                 }
84             }
85         }
86         return instance;
87     }
88
89     public JGossipLog() throws SystemException {
90         try {
91             Properties JavaDoc prop = new Properties JavaDoc();
92             prop.load(getClass().getClassLoader().getResourceAsStream(
93                     "org/jresearch/gossip/resources/log.properties"));
94             boolean writeToFile = "c".equalsIgnoreCase(prop
95                     .getProperty("logs.type"));
96             // *************************** create and configure app logger
97

98             appLogger = Hierarchy.getDefaultHierarchy().getLoggerFor(
99                     IConst.LOG.APPLICATION_LOG_NAME);
100             String JavaDoc logLevel = prop.getProperty("logs.level");
101             if (null == logLevel)
102                 logLevel = "DEBUG";
103
104             Priority priority = Priority.getPriorityForName(logLevel);
105             appLogger.setPriority(priority);
106
107             final PatternFormatter appformatter = new PatternFormatter(prop
108                     .getProperty("logs.pattern.application"));
109
110             LogTarget[] appLoggerTargets = new LogTarget[writeToFile ? 2 : 1];
111
112             appLoggerTargets[0] = new WriterTarget(new PrintWriter JavaDoc(System.out),
113                     appformatter);
114             if (writeToFile) {
115                 // open file target in append mode
116
final File JavaDoc appfile = new File JavaDoc(prop.getProperty("logs.dir")
117                         + File.separator + IConst.LOG.APPLICATION_LOG_NAME);
118
119                 appLoggerTargets[1] = new RotatingFileTarget(true,
120                         appformatter, new RotateStrategyByDate(),
121                         new UniqueFileStrategy(appfile, ".yyyy-MM-dd", ".log"));
122             }
123             // Set log targets of logger
124
appLogger.setLogTargets(appLoggerTargets);
125
126             // *************************** create and configure audit logger
127

128             auditLogger = Hierarchy.getDefaultHierarchy().getLoggerFor(
129                     IConst.LOG.AUDIT_LOG_NAME);
130             auditLogger.setPriority(Priority.INFO);
131             final PatternFormatter auditformatter = new PatternFormatter(prop
132                     .getProperty("logs.pattern.audit"));
133
134             LogTarget[] auditLoggerTargets = new LogTarget[writeToFile ? 2 : 1];
135             // create JDBC target
136
InitialContext JavaDoc ic = new InitialContext JavaDoc();
137             DataSource JavaDoc ds = (DataSource JavaDoc) ic.lookup("jgossip_db");
138
139             auditLoggerTargets[0] = new DefaultJDBCTarget(ds,
140                     IConst.LOG.LOG_TABLE, IConst.LOG.LOG_COLUMNS);
141             if (writeToFile) {
142                 // open file target in append mode
143

144                 final File JavaDoc auditfile = new File JavaDoc(prop.getProperty("logs.dir")
145                         + File.separator + IConst.LOG.AUDIT_LOG_NAME);
146
147                 auditLoggerTargets[1] = new RotatingFileTarget(
148                         true,
149                         auditformatter,
150                         new RotateStrategyByDate(),
151                         new UniqueFileStrategy(auditfile, ".yyyy-MM-dd", ".log"));
152             }
153
154             // Set log targets of logger
155
auditLogger.setLogTargets(auditLoggerTargets);
156         } catch (Exception JavaDoc e) {
157             throw new SystemException(e);
158         }
159     }
160
161     /**
162      * @return Returns the appLogger.
163      */

164     public Logger getAppLogger() {
165         return appLogger;
166     }
167
168     /**
169      * @return Returns the auditLogger.
170      */

171     public Logger getAuditLogger() {
172         return auditLogger;
173     }
174
175     /**
176      * @param level
177      * @param remoteIp
178      * @param message
179      */

180     public static void audit(LogLevel level, String JavaDoc remoteIp, String JavaDoc message) {
181         bindLogContext(" ", remoteIp, " ");
182         audit(level, message);
183     }
184
185     /**
186      * @param level
187      * @param message
188      * @param t
189      */

190     public static void audit(LogLevel level, String JavaDoc message, Throwable JavaDoc t) {
191         bindLogContext(" ", " ", " ");
192         try {
193             Logger logger = JGossipLog.getInstance().auditLogger;
194             switch (level.getLevel()) {
195             case LogLevel.ERROR_INT:
196                 logger.error(message, t);
197                 break;
198             case LogLevel.WARN_INT:
199                 logger.warn(message, t);
200                 break;
201             case LogLevel.INFO_INT:
202                 logger.info(message, t);
203                 break;
204             default:
205                 logger.debug(message, t);
206             }
207         } catch (SystemException e) {
208             e.printStackTrace();
209         }
210     }
211
212     /**
213      * @param level
214      * @param user
215      * @param message
216      * @param session
217      */

218     public static void audit(LogLevel level, User user, String JavaDoc message,
219             HttpSession JavaDoc session) {
220
221         bindLogContext((user.getName() == null) ? "<anonimous>" : user
222                 .getName(), (user.getIp() == null) ? " " : user.getIp(),
223                 session.getId());
224         audit(level, message);
225     }
226
227     private static final void audit(LogLevel level, String JavaDoc message) {
228         System.out.println(message);
229         try {
230             Logger logger = JGossipLog.getInstance().auditLogger;
231             switch (level.getLevel()) {
232             case LogLevel.ERROR_INT:
233                 logger.error(message);
234                 break;
235             case LogLevel.WARN_INT:
236                 logger.warn(message);
237                 break;
238             case LogLevel.INFO_INT:
239                 logger.info(message);
240                 break;
241             default:
242                 logger.debug(message);
243             }
244         } catch (SystemException e) {
245             e.printStackTrace();
246         }
247     }
248
249     private static SimpleDateFormat JavaDoc getDateFormat() {
250         if (dateFormat == null) {
251             synchronized (lock) {
252                 if (dateFormat == null) {
253                     dateFormat = new SimpleDateFormat JavaDoc(
254                             IConst.VALUES.ISO_DATE_FORMAT);
255                     dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
256                 }
257             }
258         }
259         return dateFormat;
260     }
261
262     private static void bindLogContext(String JavaDoc userName, String JavaDoc remoteIP,
263             String JavaDoc sessionId) {
264         final ContextMap context = new ContextMap();
265         context.set("UserName", userName);
266         context.set("RemoteIP", remoteIP);
267         context.set("SessionId", sessionId);
268         context.set("time", getDateFormat().format(new Date JavaDoc()));
269         context.makeReadOnly();
270
271         // bind new ContextMap to current thread and subthreads
272
ContextMap.bind(context);
273     }
274 }
Popular Tags