View Javadoc

1   /*
2   Copyright (c) 2005, CodeSmarts
3    All rights reserved.
4   
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions are
7   met:
8   	* 	Redistributions of source code must retain the above copyright
9   notice, this list of conditions and the following disclaimer.
10  	* 	Redistributions in binary form must reproduce the above
11  copyright notice, this list of conditions and the following disclaimer
12  in the documentation and/or other materials provided with the
13  distribution.
14  	* 	Neither the name of the CodeSmarts nor the names of its
15  contributors may be used to endorse or promote products derived from
16  this software without specific prior written permission.
17  
18  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
19  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
22  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30  
31  package net.codesmarts.log4j;
32  
33  
34  import java.io.BufferedOutputStream;
35  import java.io.File;
36  import java.io.FileOutputStream;
37  import java.io.IOException;
38  import java.util.Calendar;
39  import java.util.GregorianCalendar;
40  import java.util.Iterator;
41  import java.util.List;
42  import org.apache.log4j.spi.LoggingEvent;
43  
44  /***
45   * Log4j appender that collects logging evnets in the same thread
46   * in a common buffer
47   * 
48   * @author Fred McCann
49   */
50  public class FileSystemBugReportAppender extends AbstractBugReportAppender { 
51      
52      /***
53       * Bytes to write a new line
54       */
55      private final byte[] NEWLINE = System.getProperty("line.separator").getBytes();
56      
57      /***
58       * number of bytes to write to a file at a time
59       */
60      private final static int BUFFERSIZE = 1024;    
61  
62      /***
63       * Calendar
64       */
65      private GregorianCalendar calendar = (GregorianCalendar)Calendar.getInstance();
66      
67      /***
68       * This is where bug reports will be written
69       */
70      private String directory="."; 
71      
72      /***
73       * Extension to append to files; defaults to no extension
74       */
75      private String extension="";     
76          
77      
78      /***
79       * Initialize appender
80       */
81      public void init() {
82          File dir = new File(directory);
83          dir.mkdirs();
84          if (!dir.canWrite()) {
85              getErrorHandler().error("Can't write to directory: "+directory);
86              close();
87          }
88      }
89      
90      /***
91       * Addend a logging event
92       * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
93       */
94      public synchronized void append(BugReport report) {        
95          List events = report.getEvents();
96  
97          if (events.size()>0) {
98              LoggingEvent event; 
99  
100             // Construct filename
101             event = (LoggingEvent)events.get(0);
102             calendar.setTimeInMillis(event.timeStamp);
103             String fileName = this.directory+"/"+
104                     calendar.get(Calendar.YEAR)+"-"+
105                     calendar.get(Calendar.MONTH)+"-"+
106                     calendar.get(Calendar.DAY_OF_MONTH)+"_"+
107                     calendar.get(Calendar.HOUR)+
108                     calendar.get(Calendar.MINUTE)+
109                     calendar.get(Calendar.SECOND)+
110                     calendar.get(Calendar.MILLISECOND)+
111                     this.extension;
112                    
113             BufferedOutputStream ostream = null;
114             try {                               
115                 ostream = 
116                     new BufferedOutputStream(new FileOutputStream(fileName),BUFFERSIZE);
117                 
118                 Iterator i = events.iterator();
119                 
120                 // Write formatted events to bug report file
121                 while (i.hasNext()) {
122                     event = (LoggingEvent)i.next();
123                     String message = getLayout().format(event);
124                     
125                     if (message!=null)
126                         ostream.write(message.getBytes());
127                     
128                     String[] throwd = event.getThrowableStrRep();
129                     
130                     if (throwd!=null)
131                         for (int x=0; x<throwd.length; x++) {
132                             ostream.write(throwd[x].getBytes());
133                             ostream.write(NEWLINE);                            
134                         }
135                 }
136                 
137                 ostream.flush();           
138             }
139             catch (Exception e) {
140                 getErrorHandler().error("Error writing bug report to file: "+fileName+". "+e.getMessage());
141             }            
142             finally {
143                 try {
144                     if (ostream!=null)
145                         ostream.close();
146                 }
147                 catch (IOException e) {
148                     getErrorHandler().error("Couldn't close outputstream for : "+fileName+". "+e.getMessage());
149                 }
150             }
151         }        
152     }
153     
154     /***
155      * Get the name of the directory in which bug reports are filed
156      * @return Returns the directory.
157      */
158     public String getDirectory() {
159         return directory;
160     }
161     
162     /***
163      * Set the bug report directory. Defaults to "."
164      * @param directory The directory to set.
165      */
166     public void setDirectory(String directory) {
167         this.directory = directory;
168     }
169     
170     /***
171      * Get the extension of bug report files. Defaults to no extension
172      * @return Returns the extension.
173      */
174     public String getExtension() {
175         return extension;
176     }
177     
178     /***
179      * Set the extension of bug report files
180      * @param extension The extension to set.
181      */
182     public void setExtension(String extension) {
183         this.extension = extension;
184     }
185  
186 }