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