KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > util > webloggers > IISLogger


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.deliver.util.webloggers;
25
26 import java.io.File JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.io.RandomAccessFile JavaDoc;
30 import java.text.SimpleDateFormat JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Calendar JavaDoc;
33 import java.util.Date JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39
40 import org.infoglue.cms.util.CmsPropertyHandler;
41
42 /**
43  * The CommonLogger class implements the abstract Logger class.
44  * The resulting log will conform to the
45  * <a HREF="http://www.w3.org/Daemon/User/Config/Logging.html#common-logfile-format">common log format</a>).
46  */

47
48 public class IISLogger extends Logger
49 {
50     private final static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(IISLogger.class.getName());
51
52     protected static final String JavaDoc monthnames[] =
53     {
54     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
55     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
56     };
57     
58     protected static String JavaDoc noUrl = "*NOURL*";
59         
60
61     private byte msgbuf[] = null ;
62     protected RandomAccessFile JavaDoc log = null ;
63     protected RandomAccessFile JavaDoc errlog = null ;
64     protected RandomAccessFile JavaDoc trace = null ;
65     protected int bufsize = 8192 ;
66     protected int bufptr = 0 ;
67     protected int rotateLevel = 0 ;
68     protected byte buffer[] = null ;
69     protected int year = -1 ;
70     protected int month = -1 ;
71     protected int day = -1 ;
72     protected int hour = -1 ;
73     private Calendar JavaDoc cal = null ;
74     private long datestamp = -1 ;
75     private char datecache[] = { 'D','D','/','M','M','M',
76                            '/','Y','Y','Y','Y',':',
77                            'H','H',':','M','M',':',
78                            'S','S',' ','+','0','0',
79                            '0','0'};
80
81     private static String JavaDoc hostAddress = null;
82     private static String JavaDoc hostName = null;
83     
84     
85     /**
86      * Log the given HTTP transaction.
87      * Not implemented yet!!!
88      */

89
90     public void logRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc pagePath, long duration)
91     {
92         /*
93     Client client = request.getClient() ;
94     long date = reply.getDate();
95
96     String user = (String) request.getState(AuthFilter.STATE_AUTHUSER);
97     URL urlst = (URL) request.getState(Request.ORIG_URL_STATE);
98     String requrl;
99     if (urlst == null) {
100         URL u = request.getURL();
101         if (u == null) {
102         requrl = noUrl;
103         } else {
104         requrl = u.toExternalForm();
105         }
106     } else {
107         requrl = urlst.toExternalForm();
108     }
109     StringBuffer sb = new StringBuffer(512);
110     String logs;
111     int status = reply.getStatus();
112     if ((status > 999) || (status < 0)) {
113         status = 999; // means unknown
114     }
115     synchronized(sb) {
116         byte ib[] = client.getInetAddress().getAddress();
117         if (ib.length == 4) {
118         boolean doit;
119         for (int i=0; i< 4; i++) {
120             doit = false;
121             int b = ib[i];
122             if (b < 0) {
123             b += 256;
124             }
125             if (b > 99) {
126             sb.append((char)('0' + (b / 100)));
127             b = b % 100;
128             doit = true;
129             }
130             if (doit || (b > 9)) {
131             sb.append((char)('0' + (b / 10)));
132             b = b % 10;
133             }
134             sb.append((char)('0'+b));
135             if (i < 3) {
136             sb.append('.');
137             }
138         }
139         } else { // ipv6, let's be safe :)
140         sb.append(client.getInetAddress().getHostAddress());
141         }
142         sb.append(" - ");
143         if (user == null) {
144         sb.append("- [");
145         } else {
146         sb.append(user);
147         sb.append(" [");
148         }
149         dateCache(date, sb);
150         sb.append("] \"");
151         sb.append(request.getMethod());
152         sb.append(' ');
153         sb.append(requrl);
154         sb.append(' ');
155         sb.append(request.getVersion());
156         sb.append("\" ");
157         sb.append((char)('0'+ status / 100));
158         status = status % 100;
159         sb.append((char)('0'+ status / 10));
160         status = status % 10;
161         sb.append((char)('0'+ status));
162         sb.append(' ');
163         if (nbytes < 0) {
164         sb.append('-');
165         } else {
166         sb.append(nbytes);
167         }
168         sb.append('\n');
169         logs = sb.toString();
170     }
171     logmsg(logs);
172         */

173     }
174
175
176         
177     /**
178      * Initialize this logger for the given server.
179      * This method gets the server properties describe above to
180      * initialize its various log files.
181      * @param server The server to which thiss logger should initialize.
182      */

183
184     public void initialize()
185     {
186     }
187     
188     /**
189      * Construct a new Logger instance.
190      */

191
192     IISLogger()
193     {
194         this.msgbuf = new byte[128] ;
195     }
196
197     private String JavaDoc headerLine1 = "#Software: Microsoft Internet Information Services 5.0";
198     private String JavaDoc headerLine2 = "#Version: 1.0";
199     private String JavaDoc headerLine3 = "#Date: " + new Date JavaDoc();
200     private String JavaDoc headerLine4 = "#Fields: date time c-ip cs-username s-sitename s-computername s-ip s-port cs-method cs-uri-stem cs-uri-query sc-status sc-win32-status sc-bytes cs-bytes time-taken cs-version cs-host cs(User-Agent) cs(Cookie) cs(Referer)";
201     
202     
203     private List JavaDoc logBuffer = new ArrayList JavaDoc();
204     
205     /**
206      * This method writes a request to the logfile
207      */

208     
209     protected void writeRequest(String JavaDoc date, String JavaDoc row)
210     {
211         logBuffer.add(row);
212         
213         if(logBuffer.size() > 20)
214         {
215             String JavaDoc logPath = CmsPropertyHandler.getStatisticsLogPath();
216             File JavaDoc file = new File JavaDoc(logPath + File.separator + "stat" + date + ".log");
217             boolean isFileCreated = file.exists();
218                 
219             PrintWriter JavaDoc pout = null;
220             try
221             {
222                 pout = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(file, true));
223                 if(!isFileCreated)
224                 {
225                     pout.println(headerLine1);
226                     pout.println(headerLine2);
227                     pout.println(headerLine3);
228                     pout.println(headerLine4);
229                 }
230             
231                 Iterator JavaDoc i = logBuffer.iterator();
232                 while(i.hasNext())
233                 {
234                     pout.println(i.next().toString());
235                 }
236                 pout.close();
237             }
238             catch(Exception JavaDoc e)
239             {
240                 logger.error(e.getMessage(), e);
241             }
242             finally
243             {
244                 try
245                 {
246                     pout.close();
247                 }
248                 catch(Exception JavaDoc e)
249                 {
250                 }
251             }
252             
253             logBuffer = new ArrayList JavaDoc();
254         }
255     }
256     
257     
258     /**
259      * This method returns a date as a string.
260      */

261     
262     public String JavaDoc getCurrentDate(String JavaDoc pattern)
263     {
264         /*
265         SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
266         pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
267         pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
268         */

269         // Format the current time.
270
Date JavaDoc date = new Date JavaDoc();
271         SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc(pattern);
272         String JavaDoc dateString = formatter.format(date);
273         return dateString;
274     }
275     
276     
277     public String JavaDoc getHostAddress()
278     {
279         if(hostAddress != null)
280             return hostAddress;
281             
282         String JavaDoc address = null;
283         
284         try
285         {
286             address = java.net.InetAddress.getLocalHost().getHostAddress();
287         }
288         catch(Exception JavaDoc e)
289         {
290             logger.error(e.getMessage(), e);
291         }
292         
293         hostAddress = address;
294         
295         return address;
296     }
297
298     public String JavaDoc getHostName()
299     {
300         if(hostName != null)
301             return hostName;
302
303         String JavaDoc name = null;
304         
305         try
306         {
307             name = java.net.InetAddress.getLocalHost().getHostName();
308         }
309         catch(Exception JavaDoc e)
310         {
311             logger.error(e.getMessage(), e);
312         }
313         
314         hostName = name;
315         
316         return name;
317     }
318
319     
320     public String JavaDoc defaultValueIfNull(String JavaDoc value)
321     {
322         if(value == null || value.equals(""))
323             return "-";
324     
325         return value;
326     }
327 }
328
329
330
331
Popular Tags