Debian Codegraph @

src/uk/me/parabola/log/Logger.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 30-Dec-2006
16 */
17 package uk.me.parabola.log;
18
19 import java.io.FileInputStream;
20 import java.io.FileNotFoundException;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.Properties;
24 import java.util.logging.ConsoleHandler;
25 import java.util.logging.Level;
26 import java.util.logging.LogManager;
27
28 /**
29 * Simple logging class. By default it is disabled. You have to set it up
30 * using (currently) a system property. On the other hand it uses varargs
31 * to make easier logging without having to do string concatenation in the
32 * regular code.
33 *
34 * @author Steve Ratcliffe
35 */
36 public class Logger {
37 private final java.util.logging.Logger log;
38 private final boolean addPrefix;
39 public static final Logger defaultLogger = new Logger(java.util.logging.Logger.GLOBAL_LOGGER_NAME, false);
40
41 private static final ThreadLocal<String> threadTags = new ThreadLocal<>();
42
43 static {
44 initLogging();
45 }
46
47 private Logger(String name, boolean addPrefix) {
48 this.log = java.util.logging.Logger.getLogger(name);
49 this.addPrefix = addPrefix;
50 }
51
52 /**
53 * Get a logger by its name.
54 *
55 * @param name The name of the logger. Uses the same conventions as in
56 * java.util.logging.Logger as this is just a thin wrapper around that
57 * class.
58 * @return The logger.
59 */
60 public static Logger getLogger(String name) {
61 return new Logger(name, true);
62 }
63
64 /**
65 * Convenience class to get a logger using a class name as the name.
66 * @param aClass The class - its name will be used to retrieve the
67 * logger.
68 * @return The logger.
69 */
70 public static Logger getLogger(Class<?> aClass) {
71 String name = aClass.getName();
72 return getLogger(name);
73 }
74
75 public static void resetLogging(String filename) {
76 initLoggingFromFile(filename);
77 }
78
79 private static void initLogging() {
80 Properties props = System.getProperties();
81
82 String logconf = props.getProperty("log.config");
83 if (logconf != null) {
84 initLoggingFromFile(logconf);
85 }
86 else {
87 staticSetup();
88 }
89 if (!defaultLogger.isLoggable(Level.WARNING))
90 defaultLogger.log.setLevel(Level.WARNING);
91 }
92
93 private static void initLoggingFromFile(String logconf) {
94 try {
95 InputStream in = new FileInputStream(logconf);
96 LogManager lm = LogManager.getLogManager();
97 lm.reset();
98 lm.readConfiguration(in);
99 } catch (FileNotFoundException e) {
100 System.err.println("Failed to open logging config file " + logconf);
101 staticSetup();
102 } catch (IOException e) {
103 staticSetup();
104 }
105 }
106
107 /**
108 * The default setup, which is basically not to do any logging apart from
109 * showing errors.
110 */
111 private static void staticSetup() {
112 // Static setup.
113 LogManager.getLogManager().reset();
114 java.util.logging.Logger l = java.util.logging.Logger.getLogger("");
115
116 ConsoleHandler handler = new ConsoleHandler();
117 UsefulFormatter f = new UsefulFormatter();
118
119 f.setShowTime(false);
120
121 handler.setFormatter(f);
122 handler.setLevel(Level.FINE);
123
124 l.addHandler(handler);
125 l.setLevel(Level.SEVERE);
126 }
127
128 public boolean isLoggable(Level level) {
129 return log.isLoggable(level);
130 }
131
132 public boolean isDebugEnabled() {
133 return log.isLoggable(Level.FINE);
134 }
135
136 public boolean isInfoEnabled() {
137 return log.isLoggable(Level.INFO);
138 }
139
140 /**
141 * Debug message. We are using the j.u.l FINE level for this. As it is
142 * possible that the toString method on the logged object is expensive
143 * we check that the message should be logged first. Though this is
144 * perhaps overkill.
145 *
146 * This comment applies to all the corresponding methods below.
147 *
148 * @param o The object to be logged.
149 */
150 public void debug(Object o) {
151 if (log.isLoggable(Level.FINE))
152 log.fine(tagMessage(o == null? "null" : o.toString()));
153 }
154
155 /**
156 * Log a message that consists of a variable number of arguments. The
157 * arguments are simply concatenated with a space between them.
158 *
159 * The arrayFormat call is very expensive and checking the log level first
160 * is important. The same applies to all similar routines below.
161 *
162 * @param olist The list of objects to log as one message.
163 */
164 public void debug(Object ... olist) {
165 if (log.isLoggable(Level.FINE))
166 arrayFormat(Level.FINE, olist);
167 }
168
169 public void info(Object o) {
170 if (log.isLoggable(Level.INFO))
171 log.info(tagMessage(o == null? "null" : o.toString()));
172 }
173
174 public void info(Object ... olist) {
175 if (log.isLoggable(Level.INFO))
176 arrayFormat(Level.INFO, olist);
177 }
178
179 public void infof(String fmt, Object... args) {
180 if (log.isLoggable(Level.INFO))
181 printf(Level.INFO, fmt, args);
182 }
183
184 public void warn(Object o) {
185 if (log.isLoggable(Level.WARNING))
186 log.warning(tagMessage(o == null? "null" : o.toString()));
187 }
188
189 public void warn(Object ... olist) {
190 if (log.isLoggable(Level.WARNING))
191 arrayFormat(Level.WARNING, olist);
192 }
193
194 public void warnf(String fmt, Object... args) {
195 if (log.isLoggable(Level.WARNING))
196 printf(Level.WARNING, fmt, args);
197 }
198
199 public void error(Object o) {
200 log.severe(tagMessage(o == null? "null" : o.toString()));
201 }
202
203 public void error(Object ... olist) {
204 arrayFormat(Level.SEVERE, olist);
205 }
206
207 public void errorf(String fmt, Object... args) {
208 printf(Level.SEVERE, fmt, args);
209 }
210
211 public void error(Object o, Throwable e) {
212 log.log(Level.SEVERE, tagMessage(o == null? "null" : o.toString()), e);
213 }
214
215 // output a requested diagnostic message
216 public void diagnostic(String msg) {
217 log.log(LogLevel.DIAGNOSTIC, tagMessage(msg));
218 }
219
220 // output an echo or echotags message
221 public void echo(String msg) {
222 log.log(LogLevel.ECHO, tagMessage(msg));
223 }
224
225 // an information message that is always output
226 public void write(String msg) {
227 log.log(LogLevel.OVERRIDE, tagMessage(msg));
228 }
229
230 public void log(Level level, Object o) {
231 if (log.isLoggable(level))
232 log.log(level, tagMessage(o == null? "null" : o.toString()));
233 }
234
235 public void log(Level level, Object ... olist) {
236 if (log.isLoggable(level))
237 arrayFormat(level, olist);
238 }
239
240 /**
241 * Format the list of arguments by appending them to one string, keeping a
242 * space between them.
243 *
244 * Only call this if you've checked that the message needs to be printed,
245 * otherwise it will all go to waste.
246 *
247 * @param type The Level type FINE, INFO etc.
248 * @param olist The argument list as objects.
249 */
250 private void arrayFormat(Level type, Object... olist) {
251 if (log.isLoggable(type)) {
252 StringBuilder sb = new StringBuilder();
253 for (Object o : olist) {
254 sb.append(o);
255 sb.append(' ');
256 }
257 sb.setLength(sb.length()-1);
258 log.log(type, tagMessage(sb.toString()));
259 }
260 }
261
262 private void printf(Level type, String fmt, Object... args) {
263 if (log.isLoggable(type)) {
264 String msg = String.format(fmt, args);
265 log.log(type, tagMessage(msg));
266 }
267 }
268
269 private String tagMessage(String message) {
270 if (!addPrefix)
271 return message;
272
273 String threadTag = threadTags.get();
274 return (threadTag != null) ? threadTag + ": " + message : message;
275 }
276
277 public void threadTag(String tag) {
278 threadTags.set(tag);
279 }
280
281 public String threadTag() {
282 return threadTags.get();
283 }
284 }