1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.allanbank.mongodb.util.log;
21
22 import java.util.logging.Level;
23 import java.util.logging.LogRecord;
24 import java.util.logging.Logger;
25
26
27
28
29
30
31
32
33 public class JulLog extends AbstractLog {
34
35
36 private final Logger myDelegate;
37
38
39
40
41
42
43
44 protected JulLog(final Class<?> clazz) {
45 myDelegate = Logger.getLogger(clazz.getName());
46 }
47
48
49
50
51
52
53
54
55
56 @Override
57 protected final void doLog(final Level level, final Throwable thrown,
58 final String template, final Object... args) {
59 if (myDelegate.isLoggable(level)) {
60
61 final Thread currentThread = Thread.currentThread();
62 final LogRecord record = new LogRecord(level,
63 format(template, args));
64 record.setLoggerName(myDelegate.getName());
65 record.setThrown(thrown);
66 record.setThreadID((int) Thread.currentThread().getId());
67
68
69
70
71 boolean lookingForThisClass = true;
72 for (final StackTraceElement element : currentThread
73 .getStackTrace()) {
74 final String className = element.getClassName();
75
76
77 if (lookingForThisClass) {
78 lookingForThisClass = !CLASS_NAME.equals(className);
79 }
80 else {
81
82 if (!CLASS_NAME.equals(className)) {
83 record.setSourceClassName(className);
84 record.setSourceMethodName(element.getMethodName());
85 break;
86 }
87 }
88 }
89
90
91 myDelegate.log(record);
92 }
93 }
94
95
96
97
98
99
100
101
102
103
104
105 private String format(final String template, final Object[] args) {
106 String result = template;
107 if ((args != null) && (args.length > 0)
108 && (template.indexOf(REPLACE_TOKEN) >= 0)) {
109
110 final StringBuilder builder = new StringBuilder(template.length());
111 for (final Object arg : args) {
112 final int index = result.indexOf(REPLACE_TOKEN);
113 if (index < 0) {
114 break;
115 }
116
117 builder.append(result.substring(0, index));
118 builder.append(arg);
119 result = result.substring(index + 2);
120 }
121
122 builder.append(result);
123 result = builder.toString();
124 }
125 return result;
126 }
127
128 }