1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  package ch.qos.logback.classic.multiJVM;
15  
16  import org.slf4j.Logger;
17  
18  import ch.qos.logback.classic.LoggerContext;
19  import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
20  import ch.qos.logback.classic.spi.ILoggingEvent;
21  import ch.qos.logback.core.FileAppender;
22  
23  
24  
25  
26  
27  
28  
29  public class SafeModeFileAppender {
30  
31      static long LEN;
32      static String FILENAME;
33      static String STAMP;
34  
35      static public void main(String[] argv) throws Exception {
36          if (argv.length != 3) {
37              usage("Wrong number of arguments.");
38          }
39  
40          STAMP = argv[0];
41          LEN = Integer.parseInt(argv[1]);
42          FILENAME = argv[2];
43          writeContinously(STAMP, FILENAME, true);
44      }
45  
46      static void usage(String msg) {
47          System.err.println(msg);
48          System.err.println("Usage: java " + SafeModeFileAppender.class.getName() + " stamp runLength filename\n"
49                  + " stamp JVM instance stamp\n" + "   runLength (integer) the number of logs to generate perthread"
50                  + "    filename (string) the filename where to write\n");
51          System.exit(1);
52      }
53  
54      static LoggerContext buildLoggerContext(String stamp, String filename, boolean safetyMode) {
55          LoggerContext loggerContext = new LoggerContext();
56  
57          FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();
58  
59          PatternLayoutEncoder patternLayout = new PatternLayoutEncoder();
60          patternLayout.setPattern(stamp + " %5p - %m%n");
61          patternLayout.setContext(loggerContext);
62          patternLayout.start();
63  
64          fa.setEncoder(patternLayout);
65          fa.setFile(filename);
66          fa.setAppend(true);
67          fa.setPrudent(safetyMode);
68          fa.setContext(loggerContext);
69          fa.start();
70  
71          ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
72          root.addAppender(fa);
73  
74          return loggerContext;
75      }
76  
77      static void writeContinously(String stamp, String filename, boolean safetyMode) throws Exception {
78          LoggerContext lc = buildLoggerContext(stamp, filename, safetyMode);
79          Logger logger = lc.getLogger(SafeModeFileAppender.class);
80  
81          long before = System.nanoTime();
82          for (int i = 0; i < LEN; i++) {
83              logger.debug(LoggingThread.msgLong + " " + i);
84          }
85          lc.stop();
86          double durationPerLog = (System.nanoTime() - before) / (LEN * 1000.0);
87  
88          System.out.println(
89                  "Average duration of " + (durationPerLog) + " microseconds per log. Safety mode " + safetyMode);
90          System.out.println("------------------------------------------------");
91      }
92  }