aboutsummaryrefslogtreecommitdiffstats
path: root/vespalog/src/main/java/com/yahoo/log/VespaFormatter.java
blob: dff8606cbba3dbe7b420abf4a7669f32760d323a (plain) (blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// $Id$
package com.yahoo.log;

import com.yahoo.log.event.Event;
import com.yahoo.log.impl.LogUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class implements a log formatter which takes care of
 * formatting messages according to the VESPA common log format.
 *
 * @author  Bjorn Borud
 * @author arnej27959
 *
 */
class VespaFormatter extends SimpleFormatter {

    private static final Pattern backSlash = Pattern.compile("\\\\");

    // other way around
    private static final Pattern backSlashN = Pattern.compile("\\\\n");
    private static final Pattern backSlashT = Pattern.compile("\\\\t");
    private static final Pattern backSlash2 = Pattern.compile("\\\\\\\\");

    private static final String hostname;
    private static final String processID;

    public static final String serviceNameUnsetValue = "-";

    static {
        hostname = LogUtils.getHostName();
        processID = LogUtils.getPID();
    }

    private String serviceName;
    private final String componentPrefix;

    /**
     * Default constructor
     */
    public VespaFormatter() {
        this.serviceName = serviceNameUnsetValue;
        this.componentPrefix = null;
    }

    /**
     * @param serviceName The VESPA service name.
     * @param componentPrefix The application name.
     */
    public VespaFormatter(String serviceName, String componentPrefix) {
        if (serviceName == null) {
            this.serviceName = serviceNameUnsetValue;
        } else {
            this.serviceName = serviceName;
        }
        this.componentPrefix = componentPrefix;
    }

    /**
     * Un-escapes previously escaped string.
     * note: look at com.yahoo.config.StringNode.unescapeQuotedString()
     *
     * @param s String that might need un-escaping
     * @return Returns un-escaped string
     */
    public static String unEscape(String s) {
        Matcher m = backSlash.matcher(s);
        if (! m.find()) {
            return s;
        }
        m = backSlashN.matcher(s);
        if (m.find()) {
            s = m.replaceAll("\n");
        }
        m = backSlashT.matcher(s);
        if (m.find()) {
            s = m.replaceAll("\t");
        }
        m = backSlash2.matcher(s);
        if (m.find()) {
            s = m.replaceAll("\\\\");
        }
        return s;
    }

    @SuppressWarnings("deprecation")
    public String format(LogRecord r) {
        StringBuilder sbuf = new StringBuilder(300); // initial guess

        String levelName = LogLevel.getVespaLogLevel(r.getLevel()).toString().toLowerCase();

        String component = r.getLoggerName();

        // format the time
        sbuf.append(VespaFormat.formatTime(r.getInstant()));
        sbuf.append("\t");

        sbuf.append(hostname).append("\t")
            .append(processID).append("/")
            .append(r.getThreadID()).append("\t")
            .append(serviceName).append("\t");

        if (component == null && componentPrefix == null) {
            sbuf.append("-");
        } else if (component == null) {
            sbuf.append(componentPrefix);
        } else if (componentPrefix == null) {
            sbuf.append(".").append(component);
        } else {
            sbuf.append(componentPrefix).append(".").append(component);
        }

        sbuf.append("\t").append(levelName).append("\t");

        // for events, there is no ordinary message string;
        // instead we render a string represantion of the event object:
        if (r.getLevel() == LogLevel.EVENT) {
            Event event = (Event) r.getParameters()[0];
            sbuf.append(VespaFormat.escape(event.toString()));
        } else {
            // otherwise, run standard java text formatting on the message
            sbuf.append(VespaFormat.escape(formatMessage(r)));
        }
        appendException(r.getThrown(), sbuf);

        sbuf.append("\n");
        return sbuf.toString();
    }

    private void appendException(Throwable throwable, StringBuilder builder) {
        if (throwable == null)
            return;

        String escapedStackTrace = VespaFormat.escape(stackTrace(throwable));
        builder.append("\\n").append("exception=").append("\\n").append(escapedStackTrace);
    }

    private String stackTrace(Throwable throwable) {
        StringWriter writer = new StringWriter();
        PrintWriter wrappedWriter = new PrintWriter(writer);
        throwable.printStackTrace(wrappedWriter);
        wrappedWriter.close();
        return writer.toString();
    }


    /**
     * Set the service name (usually the VESPA config-id) of this
     * formatter.
     *
     * @param serviceName The service name
     */
    public void setServiceName (String serviceName) {
        this.serviceName = serviceName;
    }

    /**
     * Get the service name for this formatter.
     *
     * @return Returns the service name.
     */
    public String getServiceName () {
        return serviceName;
    }


    public static String toMessageString(Throwable t) {
        StringBuilder b = new StringBuilder();
        String lastMessage = null;
        String message;
        for (; t != null; t = t.getCause()) {
            message = getMessage(t);
            if (message == null) continue;
            if (message.equals(lastMessage)) continue;
            if (b.length() > 0) {
                b.append(": ");
            }
            b.append(message);
            lastMessage = message;
        }
        return b.toString();
    }

    /** Returns a useful message from *this* exception, or null if there is nothing useful to return */
    private static String getMessage(Throwable t) {
        String message = t.getMessage();
        if (t.getCause() == null) {
            if (message == null) return t.getClass().getSimpleName();
        }
        return message;
    }


}