View Javadoc
1   /*
2    * #%L
3    * IsisFish
4    * 
5    * $Id: LoggerHelper.java 4301 2015-09-29 16:46:43Z echatellier $
6    * $HeadURL: https://svn.codelutin.com/isis-fish/tags/isis-fish-4.4.0.2/src/test/java/fr/ifremer/isisfish/logging/LoggerHelper.java $
7    * %%
8    * Copyright (C) 2006 - 2010 Ifremer, Code Lutin
9    * %%
10   * This program is free software: you can redistribute it and/or modify
11   * it under the terms of the GNU General Public License as
12   * published by the Free Software Foundation, either version 3 of the 
13   * License, or (at your option) any later version.
14   * 
15   * This program is distributed in the hope that it will be useful,
16   * but WITHOUT ANY WARRANTY; without even the implied warranty of
17   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   * GNU General Public License for more details.
19   * 
20   * You should have received a copy of the GNU General Public 
21   * License along with this program.  If not, see
22   * <http://www.gnu.org/licenses/gpl-3.0.html>.
23   * #L%
24   */
25  
26  package fr.ifremer.isisfish.logging;
27  
28  import java.io.BufferedWriter;
29  import java.io.File;
30  import java.io.FileWriter;
31  import java.io.IOException;
32  import java.io.UnsupportedEncodingException;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.nuiton.util.StringUtil;
37  
38  /**
39   * Usefull methods for tests.
40   *
41   * @author chemit
42   */
43  public abstract class LoggerHelper {
44  
45      public static String filename;
46      public static long MEGA_STREAM_SIZE = 6 * 100000;
47      private static long totalPause;
48  
49      protected static final Log log = LogFactory.getLog(LoggerHelper.class);
50  
51      public static void createMock(File testDir, String filename, int i) throws IOException, InterruptedException {
52          LoggerHelper.MEGA_STREAM_SIZE = 6 * i;
53          LoggerHelper.filename = new File(testDir, filename).getAbsolutePath();
54          File file = new File(testDir, filename);
55          long t0 = System.nanoTime();
56          mockLogFile();
57          long t1;
58  
59          t1 = System.nanoTime();
60          log.info("create [" + LoggerHelper.MEGA_STREAM_SIZE + "] in " + StringUtil.convertTime(t1 - t0) + " [file: " + file + ", length: " + StringUtil.convertMemory(file.length()) + "]");
61          System.gc();
62      }
63  
64      static void pause(long time) throws InterruptedException {
65          Thread.sleep(time);
66          totalPause += time;
67          System.gc();
68      }
69  
70      /**
71       * create a mock of logEvents
72       *
73       * @throws java.io.IOException  todo
74       * @throws InterruptedException todo
75       */
76      public static void mockLogFile() throws IOException, InterruptedException {
77          File f = new File(filename);
78          if (f.exists()) {
79              f.delete();
80          }
81          BufferedWriter s = new BufferedWriter(new FileWriter(f));
82          int MAX_0 = (int) (MEGA_STREAM_SIZE / 6);
83          int i = 0;
84          long t0, t00;
85          long t1;
86          totalPause = 0;
87          t00 = System.currentTimeMillis();
88          t0 = System.currentTimeMillis();
89          try {
90  
91              for (i = 0; i < MAX_0; i++) {
92                  LogRecord record = LogRecord.newInstance(LogLevel.FATAL, 0, i + "debug ", "ioreiovrio veuio vreupo xz xe opiu tep uxr u ", "xeoiujoiz xpo puoi rui hp", i, new String[0]);
93                  s.write(record.toString() + '\n');
94                  s.flush();
95              }
96  
97              t1 = System.currentTimeMillis();
98              log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
99              //pause(500);
100             t0 = System.currentTimeMillis();
101 
102             for (i = MAX_0; i < 2 * MAX_0; i++) {
103                 LogRecord record = LogRecord.newInstance(LogLevel.WARN, 0, i + " warn", "jkljfdjkl fdkjlkj lkjdlkfjl dfkljl dflkfdj lfdjlk fjdlkj fdl", "vmfof o rieipk?prj,anklvndfkljn gmlrtsoijrmoig", i, new String[0]);
104                 s.write(record.toString() + '\n');
105             }
106             t1 = System.currentTimeMillis();
107             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
108             //pause(500);
109             t0 = System.currentTimeMillis();
110             for (i = 2 * MAX_0; i < 3 * MAX_0; i++) {
111                 LogRecord record = LogRecord.newInstance(LogLevel.INFO, 0, i + " info", "grlgjlrmgr  jglerj mgrjm  gre pjkogremoiqp   jgpo rejopigjrej,m", "grkgherjfezoprjgbpdofajhlbnb;k nfkfjgmjmsg", i, new String[0]);
112                 s.write(record.toString() + '\n');
113             }
114             t1 = System.currentTimeMillis();
115             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
116             //pause(500);
117             t0 = System.currentTimeMillis();
118             for (i = 3 * MAX_0; i < 4 * MAX_0; i++) {
119                 LogRecord record = LogRecord.newInstance(LogLevel.DEBUG, 0, i + " debug", "grmgjueroijiorehjnjodj j gn mbr,nhltrhjjdo jp joi   jreio j", "gezoeteroiyerphehkzb,fgbd bcmsherkgheiusbcjkdvberb ", i, new String[0]);
120                 s.write(record.toString() + '\n');
121                 s.flush();
122             }
123             t1 = System.currentTimeMillis();
124             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
125             //pause(500);
126             t0 = System.currentTimeMillis();
127             for (i = 4 * MAX_0; i < 5 * MAX_0; i++) {
128                 LogRecord record = LogRecord.newInstance(LogLevel.TRACE, 0, i + " trace", "ffgkdhvlsdknjk   eriopgejo ipjiropj i io poi opijgr pe jupoieruj ga geigerihpi oeop erp ", "griofeioteogbbekjbnrjemk prejrlmekhgrehivbn   rekhgrhi ", i, new String[0]);
129                 s.write(record.toString() + '\n');
130             }
131             t1 = System.currentTimeMillis();
132             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
133             //pause(500);
134             t0 = System.currentTimeMillis();
135             for (i = 5 * MAX_0; i < 6 * MAX_0; i++) {
136                 LogRecord record = LogRecord.newInstance(LogLevel.TRACE, 0, i + " user", "grekgrhze t  e re klgre ge rgre gre gfer g rjyukj yujty reez ze fz", "gekfhezh zhrze hgerhglkrej ljbvkxdfn df,ekgrrnvkmn", i, new String[0]);
137                 s.write(record.toString() + '\n');
138                 s.flush();
139             }
140             t1 = System.currentTimeMillis();
141             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
142         } catch (OutOfMemoryError e) {
143             t1 = System.currentTimeMillis();
144             log.info("failed after | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
145             e.printStackTrace();
146         } finally {
147             if (s != null) {
148                 s.flush();
149                 s.close();
150             }
151         }
152     }
153 
154     /**
155      * create a mock of logEvents
156      *
157      * @throws java.io.IOException  todo
158      * @throws InterruptedException todo
159      */
160     public static void mockLogFile2() throws IOException, InterruptedException {
161         File f = new File(filename);
162         if (f.exists()) {
163             f.delete();
164         }
165         BufferedWriter s = new BufferedWriter(new FileWriter(f));
166         int MAX_0 = (int) (MEGA_STREAM_SIZE / 6);
167         int i = 0;
168         long t0, t00;
169         long t1;
170         totalPause = 0;
171         t00 = System.currentTimeMillis();
172         t0 = System.currentTimeMillis();
173         try {
174 
175             for (i = 0; i < MAX_0; i++) {
176                 LogRecord record = LogRecord.newInstance(LogLevel.FATAL, 0, i + "debug ", "ioreiovrio veuio vreupo xz xe opiu tep uxr u ", "xeoiujoiz xpo puoi rui hp", i, new String[0]);
177                 s.write(record.toString() + '\n');
178                 s.flush();
179             }
180 
181             t1 = System.currentTimeMillis();
182             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
183             //pause(500);
184             t0 = System.currentTimeMillis();
185 
186             for (i = MAX_0; i < 2 * MAX_0; i++) {
187                 LogRecord record = LogRecord.newInstance(LogLevel.WARN, 0, i + " warn", "jkljfdjkl fdkjlkj lkjdlkfjl dfkljl dflkfdj lfdjlk fjdlkj fdl", "vmfof o rieipk?prj,ùnklvndfkljn gmlrtsoîjrmoig", i, new String[0]);
188                 s.write(record.toString() + '\n');
189             }
190             t1 = System.currentTimeMillis();
191             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
192             //pause(500);
193             t0 = System.currentTimeMillis();
194             for (i = 2 * MAX_0; i < 3 * MAX_0; i++) {
195                 LogRecord record = LogRecord.newInstance(LogLevel.INFO, 0, i + " info", "grlgjlrmgr  jglerj mgrjm  gre pjkogremoiqp   jgpo rejopigjrej,m", "grkgherjfezoprjgbpdofùjhlbnb;k nfkfjgmjmsg", i, new String[0]);
196                 s.write(record.toString() + '\n');
197             }
198             t1 = System.currentTimeMillis();
199             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
200             //pause(500);
201             t0 = System.currentTimeMillis();
202             for (i = 3 * MAX_0; i < 4 * MAX_0; i++) {
203                 LogRecord record = LogRecord.newInstance(LogLevel.DEBUG, 0, i + " debug", "grmgjueroijiorehjnjodj j gn mbr,nhltrhjjdo jp joi   jreio j", "gezoeteroiyerphehkzb,fgbd bcmsherkgheiusbcjkdvberb ", i, new String[0]);
204                 s.write(record.toString() + '\n');
205                 s.flush();
206             }
207             t1 = System.currentTimeMillis();
208             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
209             //pause(500);
210             t0 = System.currentTimeMillis();
211             for (i = 4 * MAX_0; i < 5 * MAX_0; i++) {
212                 LogRecord record = LogRecord.newInstance(LogLevel.TRACE, 0, i + " trace", "ffgkdhvlsdknjk   eriopgejo ipjiropj i io poi opijgr pe jupoieruj g'^ geigerihpi oeop erp ", "griofeioteogbbekjbnrjemk çprejrlmekhgrehivbn   rekhgrhi ", i, new String[0]);
213                 s.write(record.toString() + '\n');
214             }
215             t1 = System.currentTimeMillis();
216             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
217             //pause(500);
218             t0 = System.currentTimeMillis();
219             for (i = 5 * MAX_0; i < 6 * MAX_0; i++) {
220                 LogRecord record = LogRecord.newInstance(LogLevel.TRACE, 0, i + " user", "grekgrhze t  e re klgre ge rgre gre gfer g rjyukj yujty reez ze fz", "gekfhezh zhrze hgerhglkrej ljbvkxdfn df,ekgrrnvkmn", i, new String[0]);
221                 s.write(record.toString() + '\n');
222                 s.flush();
223             }
224             t1 = System.currentTimeMillis();
225             log.debug("create next [" + MAX_0 + "] in " + StringUtil.convertTime(t1 - t0) + " | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
226         } catch (OutOfMemoryError e) {
227             t1 = System.currentTimeMillis();
228             log.info("failed after | total " + i + " in " + StringUtil.convertTime(t1 - totalPause - t00));
229             e.printStackTrace();
230         } finally {
231             if (s != null) {
232                 s.flush();
233                 s.close();
234             }
235         }
236     }
237 
238     /**
239      * This is a log record (says an entry of a log file). This is abstracted from any
240      * logging implementation.
241      * 
242      * To deal with log, we don't use string version stored in original log file,
243      * prefer use serialized form of a LogRecord : we keep a lot of time when using
244      * them to display them in ui, and for filtering process too.
245      * 
246      * The LogRecord unicity is base on two properties :
247      * <ul>
248      * <li>timestamp</li>
249      * <li>message</li>
250      * </ul>
251      * 
252      * We can not use only timestamp, more than one event could appear in a same
253      * timestamp.
254      * 
255      * TODO Put this code in lutinLog ?
256      *
257      * @author chemit
258      */
259     public static class LogRecord implements java.io.Serializable {
260 
261         /** the time of the event */
262         protected long timeStamp;
263 
264         /** the msg for the event */
265         protected String message;
266 
267         /** the severity of the event */
268         protected int level;
269 
270         /** the throwable details the event */
271         protected String[] throwableStrRep;
272 
273         /** origin filename of the event */
274         //protected transient String filename;
275 
276         /** origin method name of the event */
277         //protected transient String methodName;
278 
279         /** origin line number of the event */
280         //protected transient int lineNumber;
281 
282         /**
283          * the string represention of logEvent, transient since we use a lazy getter
284          * we don't need to store it.
285          * 
286          * <b>(if not transient : double the size of serialized form...)</b>
287          */
288         protected transient String text;
289 
290         /**
291          * the offset of logRecord in stream.
292          * 
293          * This is a transient property, since we compute this value when getting
294          * the LogRecord from stream
295          */
296         protected transient long offset;
297 
298         private static final long serialVersionUID = 1335077740059488080L;
299 
300         public static LogRecord newInstance(LogLevel level,
301                                             long timestamp,
302                                             String message,
303                                             String fileName,
304                                             String methodName,
305                                             int lineNumber,
306                                             String[] errors) throws UnsupportedEncodingException {
307             return new LogRecord(
308                     level == null ? LogLevel.DEBUG.ordinal() : level.ordinal(),
309                     timestamp,
310                     message,
311                     fileName,
312                     methodName,
313                     lineNumber,
314                     errors
315             );
316         }
317 
318         protected LogRecord(int level,
319                             long timestamp,
320                             String message,
321                             String filename,
322                             String methodName,
323                             int lineNumber,
324                             String[] throwableStrRep) throws UnsupportedEncodingException {
325             this.level = level;
326             this.timeStamp = timestamp;
327             //this.message = message;
328             this.message = new String((filename + ":" + lineNumber + " - " + methodName + " - " + message).getBytes("utf-8"));
329             //this.filename = filename;
330             //this.methodName = methodName;
331             //this.lineNumber = lineNumber;
332             this.throwableStrRep = throwableStrRep;
333         }
334 
335         public String getMessage() {
336             return message;
337         }
338 
339         public int getLevel() {
340             return level;
341         }
342 
343         public String[] getThrowableStrRep() {
344             return throwableStrRep;
345         }
346 
347         public long getTimeStamp() {
348             return timeStamp;
349         }
350 
351         public int getLineNumber() {
352             return 0;
353             //return lineNumber;
354         }
355 
356         public String getMethodName() {
357             return "";
358             //return methodName;
359         }
360 
361         public long getOffset() {
362             return offset;
363         }
364 
365         public void setOffset(long offset) {
366             this.offset = offset;
367         }
368 
369         /**
370          * We use a cache for the representation since we will use a lots of time.
371          *
372          * @return the String representation used to display logEvent in ui.
373          */
374         @Override
375         public String toString() {
376             if (text == null) {
377                 text = new StringBuilder(LogLevel.getLogLevel(level).toString()).
378                         append(' ').append(message).toString();
379             }
380             /*if (text == null) {
381                 text = new StringBuilder().append(LogLevel.getSimulLogLevel(level)).
382                         append(' ').append(filename).append(':').
383                         append(lineNumber).append(" - ").
384                         append(methodName).append(" - ").append(message).toString();
385             }*/
386             return text;
387         }
388 
389         /**
390          * We base the identiy of a LogEvent on the message, level and timestamp
391          *
392          * @param o object to compare
393          * @return <code>true</code> if same object
394          */
395 
396         @Override
397         public boolean equals(Object o) {
398             if (this == o) {
399                 return true;
400             }
401             if (o == null || getClass() != o.getClass()) {
402                 return false;
403             }
404 
405             LogRecord event = (LogRecord) o;
406             return timeStamp == event.timeStamp &&
407                     !(message != null ? !message.equals(event.message) :
408                             event.message != null);
409         }
410 
411         @Override
412         public int hashCode() {
413             int result;
414             result = (int) (timeStamp ^ (timeStamp >>> 32));
415             result = 31 * result + (message != null ? message.hashCode() : 0);
416             return result;
417         }
418 
419     }
420 }