PageRenderTime 32ms CodeModel.GetById 2ms app.highlight 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/mpv5/logging/Log.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 360 lines | 213 code | 34 blank | 113 comment | 34 complexity | 59bc4e403f82e6a6e3389a6276a1c8f3 MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *  
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *  
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *  
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.logging;
 18
 19import de.frame4j.io.LogHandler;
 20import java.awt.Color;
 21import java.io.File;
 22import java.io.IOException;
 23import java.io.PrintWriter;
 24import java.io.StringWriter;
 25import java.util.ArrayList;
 26import java.util.Arrays;
 27import java.util.Collections;
 28import java.util.Enumeration;
 29import java.util.List;
 30import java.util.logging.Formatter;
 31import java.util.logging.Handler;
 32import java.util.logging.Level;
 33import java.util.logging.LogManager;
 34import java.util.logging.LogRecord;
 35import java.util.logging.Logger;
 36import javax.swing.table.TableModel;
 37import mpv5.Main;
 38import mpv5.bugtracker.ExceptionHandler;
 39import mpv5.globals.Messages;
 40import mpv5.utils.files.FileReaderWriter;
 41
 42/**
 43 *
 44 * 
 45 */
 46public class Log {
 47
 48    static {
 49        
 50        Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
 51        globalLogger.addHandler(new LogHandler(new Formatter() {
 52
 53            @Override
 54            public String format(LogRecord record) {
 55                if (record != null) {
 56                    return record.getMessage();
 57                } else {
 58                    return "null";
 59                }
 60            }
 61        }) {
 62
 63            @Override
 64            public void publish(LogRecord record) {
 65                Log.Debug(this, record);
 66            }
 67
 68            @Override
 69            public void flush() {
 70            }
 71
 72            @Override
 73            public void close() throws SecurityException {
 74            }
 75        });
 76        
 77         Logger.getLogger(Log.class.getName()).log(Level.INFO,  "Yabs Logger set!");
 78    }
 79    /**
 80     *
 81     * Set the logging to NONE
 82     */
 83    public static final int LOGLEVEL_NONE = 0;
 84    /**
 85     *
 86     * Gives basic messages 
 87     */
 88    public static final int LOGLEVEL_NORMAL = 1;
 89    /**
 90     *
 91     * Produces a huge amount of messages, and error stack traces
 92     */
 93    public static final int LOGLEVEL_DEBUG = 2;
 94    private static int loglevel = 1;
 95    private static List<LogConsole> loggers = new ArrayList<LogConsole>(Arrays.asList(new LogConsole[]{(LogConsole) new YConsole()}));
 96
 97    /**
 98     * Print out a text file
 99     * @param file
100     */
101    public static void Debug(File file) {
102        PrintArray(new FileReaderWriter(file).readLines());
103    }
104
105    /**
106     * 
107     * @param source
108     * @param message
109     * @param alwaysToKonsole
110     * @deprecated Replaced with <code>Debug(Object source, Object message)</code>
111     */
112    public static void Debug(Object source, Object message, boolean alwaysToKonsole) {
113        Debug(source, message);
114    }
115
116    /**
117     * The main debug method. Logs the given message depending on the current Log level.<br/><br/>
118     * <li>LOGLEVEL_NONE = no logging</li>
119     * <li>LOGLEVEL_HIGH  = basic logging</li>
120     * <li>LOGLEVEL_DEBUG = verbose logging</li>
121     * 
122     * @param source
123     * @param message
124     */
125    public static synchronized void Debug(Object source, Object message) {
126        String sourcen;
127        if (source instanceof Class) {
128            sourcen = ((Class) source).getName();
129        } else {
130            sourcen = source.getClass().getName();
131        }
132
133        if (message instanceof Throwable) {
134            try {
135                ExceptionHandler.add((Exception) message);
136            } catch (Exception e) {
137                Print(e);
138            }
139        }
140
141        switch (loglevel) {
142            case LOGLEVEL_DEBUG:
143                writeDirect(sourcen + ": " + message);
144                if (message != null && message instanceof Throwable) {
145                    ((Throwable) message).printStackTrace();
146                    writeDirect(getStackTrace(((Throwable) message)));
147                    writeDirect("\nCaused by:\n");
148                    try {
149                        ((Exception) message).getCause().printStackTrace();
150                        writeDirect(getStackTrace(((Throwable) message).getCause()));
151                        mpv5.YabsViewProxy.instance().addMessage(Messages.ERROR_OCCURED + ". " + Messages.SEE_LOG, Color.RED);
152                    } catch (Exception e) {
153                    }
154                }
155                break;
156            case LOGLEVEL_NORMAL:
157                if (message != null && (message.toString().contains("Exception") || message.toString().contains("Error"))) {
158                    write(sourcen + ": " + message);
159                    mpv5.YabsViewProxy.instance().addMessage(Messages.ERROR_OCCURED + ". " + Messages.SEE_LOG, Color.RED);
160                }
161                break;
162            case LOGLEVEL_NONE:
163                break;
164            default:
165                write(sourcen + ": " + message);
166        }
167    }
168
169    /**
170     * Prints messages, regardless the log level
171     * @param message
172     */
173    public static void Print(Object... message) {
174        for (int i = 0; i < message.length; i++) {
175            Object object = message[i];
176            write(object);
177            if (!YConsole.CONSOLE_LOG_ENABLED) {
178                System.out.println(object);
179            }
180        }
181    }
182
183    /**
184     * Print an array
185     * @param array
186     */
187    public static void PrintArray(Object[][][] array) {
188        write("Print array: {");
189        if (loglevel != LOGLEVEL_NONE) {
190            for (int i = 0; i < array.length; i++) {
191                write("");
192                for (int k = 0; k < array[i].length; k++) {
193                    write("");
194                    for (int f = 0; f < array[i][k].length; f++) {
195                        write(array[i][k][f] + " ");
196                    }
197                }
198            }
199        }
200        write("}//End Print array");
201    }
202
203    /**
204     * Print an array
205     * @param array
206     */
207    public static void PrintArray(Object[][] array) {
208        write("Print array: {");
209        for (int i = 0; i < array.length; i++) {
210            for (int k = 0; k < array[i].length; k++) {
211                if (loglevel != LOGLEVEL_NONE) {
212                    write("[" + i + "]" + " [" + k + "] " + array[i][k]);
213                }
214            }
215        }
216        write("}//End Print array");
217    }
218
219    /**
220     * Print an array
221     * @param string
222     */
223    public static void PrintArray(Object[] string) {
224        write("Print array: {");
225        if (loglevel != LOGLEVEL_NONE) {
226            write(Arrays.asList(string));
227        }
228        write("}//End Print array");
229    }
230
231    /**
232     * Print a list
233     * @param lst
234     */
235    public static void PrintArray(List lst) {
236        for (int idx = 0; idx < lst.size(); idx++) {
237            write(lst.get(idx));
238        }
239    }
240
241    private static synchronized void write(final Object obj) {
242        Runnable runnable = new Runnable() {
243
244            public void run() {
245                for (int i = 0; i < loggers.size(); i++) {
246                    loggers.get(i).log(obj);
247                    ;
248                }
249            }
250        };
251        Thread thread = new Thread(runnable);
252        thread.start();
253    }
254
255    private static synchronized void writeDirect(final Object obj) {
256        for (int i = 0; i < loggers.size(); i++) {
257            loggers.get(i).log(obj);
258        }
259    }
260
261    /**
262     * Debug an Exception
263     * @param ex
264     */
265    public static void Debug(Throwable ex) {
266        Debug(Log.class, ex);
267    }
268
269    /**
270     *
271     * @return
272     */
273    public static List<LogConsole> getLogger() {
274        return Collections.unmodifiableList(loggers);
275    }
276
277    /**
278     * Set the log level<br/>
279     * <li>LOGLEVEL_NONE = no logging</li>
280     * <li>LOGLEVEL_HIGH  = basic logging</li>
281     * <li>LOGLEVEL_DEBUG = verbose logging</li>
282     * @param level
283     */
284    public static void setLogLevel(int level) {
285        Log.setLoglevel(level);
286    }
287
288    /**
289     * Print a table model
290     * @param model
291     */
292    public static void PrintArray(TableModel model) {
293        for (int i = 0; i < model.getRowCount(); i++) {
294            for (int j = 0; j < model.getColumnCount(); j++) {
295                write(model.getValueAt(i, j));
296            }
297        }
298    }
299
300    /**
301     *
302     */
303    public static void PrintArray(Enumeration<String> keys) {
304        while (keys.hasMoreElements()) {
305            Print(keys.nextElement());
306        }
307    }
308
309    /**
310     * @param aLoglevel the loglevel to set
311     */
312    public static void setLoglevel(int aLoglevel) {
313        loglevel = aLoglevel;
314    }
315
316    /**
317     * @param aLogger the logger to set
318     */
319    public static void setLogger(LogConsole aLogger) {
320        loggers.clear();
321        loggers.add(aLogger);
322    }
323
324    public static void addLogger(LogConsole logConsole) {
325        loggers.add(logConsole);
326    }
327
328    /**
329     * 
330     * @return 
331     */
332    public static boolean isDebugging() {
333        return loglevel == LOGLEVEL_DEBUG;
334    }
335
336    private Log() {
337    }
338
339    /**
340     *
341     * @return The current log level
342     */
343    public static int getLoglevel() {
344        return loglevel;
345    }
346
347    /**
348     * Writes the stacktrace to a String
349     * @param t
350     * @return
351     */
352    public static String getStackTrace(Throwable t) {
353        StringWriter sw = new StringWriter();
354        PrintWriter pw = new PrintWriter(sw, true);
355        t.printStackTrace(pw);
356        pw.flush();
357        sw.flush();
358        return sw.toString();
359    }
360}