summaryrefslogtreecommitdiff
path: root/src/traffic-incidents-service/org.genivi.trafficinfo.demo/src/org/genivi/trafficinfo/demo/logging/EclipseConsoleFormatter.java
blob: 59b1f4e096775cee9f0436d2badac80c6eda9ad3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * 
 * Copyright (C) 2013 TomTom International B.V.
 * 
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 * 
 */
package org.genivi.trafficinfo.demo.logging;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;

public class EclipseConsoleFormatter extends SimpleFormatter {
  private final static String LOGGER = "java.util.logging.Logger";
  private static final String NEW_LINE = System.getProperty("line.separator");

  @Override
  public String format(LogRecord record) {
    String fileName = null;
    String className = null;
    String methodName = null;
    int lineNumber = -1;
    
    boolean loggerFound = false;
    for ( StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace() ) {
      className = stackTraceElement.getClassName();
      
      if (!loggerFound) {
        if (className.equals(LOGGER)) {
          loggerFound = true;
          continue;
        }
      }
      
      
      if (loggerFound && !className.equals(LOGGER)) {
        className = className.substring(className.lastIndexOf(".") + 1);
        fileName = stackTraceElement.getFileName();
        methodName = stackTraceElement.getMethodName();
        lineNumber = stackTraceElement.getLineNumber();
        break;
      }
    }
        
    StringBuilder buf = new StringBuilder();
    buf.append(className);
    buf.append(".");
    buf.append(methodName);
    buf.append(": ");
    buf.append(formatMessage(record));
    
    if (record.getThrown() != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println();
        record.getThrown().printStackTrace(pw);
        pw.close();
        buf.append(sw.toString());
    }
    
    buf.append(" (");
    buf.append(fileName);
    buf.append(":");
    buf.append(lineNumber);
    buf.append(")");
    buf.append(NEW_LINE);
        
    return buf.toString();
  }

}