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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.valves;
import java.io.CharArrayWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.tomcat.util.json.JSONFilter;
/**
* Access log valve derivative that rewrites entries as JSON.
* <p>
* <b>Important note: the attribute names are not final.</b>
* <p>
* Patterns are mapped to attributes as followed:
* <ul>
* <li>a: remoteAddr</li>
* <li>A: localAddr</li>
* <li>b: size (byteSent: size)</li>
* <li>B: byteSentNC</li>
* <li>D: elapsedTime</li>
* <li>F: firstByteTime</li>
* <li>h: host</li>
* <li>H: protocol</li>
* <li>l: logicalUserName</li>
* <li>m: method</li>
* <li>p: port</li>
* <li>q: query</li>
* <li>r: request</li>
* <li>s: statusCode</li>
* <li>S: sessionId</li>
* <li>t: time (dateTime: time)</li>
* <li>T: elapsedTimeS</li>
* <li>u: user</li>
* <li>U: path (requestURI: path)</li>
* <li>v: localServerName</li>
* <li>I: threadName</li>
* <li>X: connectionStatus</li>
* <li>%{xxx}a: remoteAddress-xxx</li>
* <li>%{xxx}p: port-xxx</li>
* <li>%{xxx}t: time-xxx</li>
* <li>%{xxx}c: cookies</li>
* <li>%{xxx}i: requestHeaders</li>
* <li>%{xxx}o: responseHeaders</li>
* <li>%{xxx}r: requestAttributes</li>
* <li>%{xxx}s: sessionAttributes</li>
* <li>%{xxx}L: identifier</li>
* </ul>
* The attribute list is based on
* <a href="https://github.com/fluent/fluentd/blob/master/lib/fluent/plugin/parser_apache2.rb#L72">parser_apache2.rb</a>
*/
public class JsonAccessLogValve extends AccessLogValve {
private static final Map<Character,String> PATTERNS;
static {
Map<Character,String> pattern2AttributeName = new HashMap<>();
pattern2AttributeName.put(Character.valueOf('a'), "remoteAddr");
pattern2AttributeName.put(Character.valueOf('A'), "localAddr");
pattern2AttributeName.put(Character.valueOf('b'), "size");
pattern2AttributeName.put(Character.valueOf('B'), "byteSentNC");
pattern2AttributeName.put(Character.valueOf('D'), "elapsedTime");
pattern2AttributeName.put(Character.valueOf('F'), "firstByteTime");
pattern2AttributeName.put(Character.valueOf('h'), "host");
pattern2AttributeName.put(Character.valueOf('H'), "protocol");
pattern2AttributeName.put(Character.valueOf('I'), "threadName");
pattern2AttributeName.put(Character.valueOf('l'), "logicalUserName");
pattern2AttributeName.put(Character.valueOf('m'), "method");
pattern2AttributeName.put(Character.valueOf('p'), "port");
pattern2AttributeName.put(Character.valueOf('q'), "query");
pattern2AttributeName.put(Character.valueOf('r'), "request");
pattern2AttributeName.put(Character.valueOf('s'), "statusCode");
pattern2AttributeName.put(Character.valueOf('S'), "sessionId");
pattern2AttributeName.put(Character.valueOf('t'), "time");
pattern2AttributeName.put(Character.valueOf('T'), "elapsedTimeS");
pattern2AttributeName.put(Character.valueOf('u'), "user");
pattern2AttributeName.put(Character.valueOf('U'), "path");
pattern2AttributeName.put(Character.valueOf('v'), "localServerName");
pattern2AttributeName.put(Character.valueOf('X'), "connectionStatus");
PATTERNS = Collections.unmodifiableMap(pattern2AttributeName);
}
private static final Map<Character,String> SUB_OBJECT_PATTERNS;
static {
Map<Character,String> pattern2AttributeName = new HashMap<>();
pattern2AttributeName.put(Character.valueOf('c'), "cookies");
pattern2AttributeName.put(Character.valueOf('i'), "requestHeaders");
pattern2AttributeName.put(Character.valueOf('o'), "responseHeaders");
pattern2AttributeName.put(Character.valueOf('r'), "requestAttributes");
pattern2AttributeName.put(Character.valueOf('s'), "sessionAttributes");
pattern2AttributeName.put(Character.valueOf('L'), "identifier");
SUB_OBJECT_PATTERNS = Collections.unmodifiableMap(pattern2AttributeName);
}
/**
* write any char
*/
protected static class CharElement implements AccessLogElement {
private final char ch;
public CharElement(char ch) {
this.ch = ch;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
buf.write(ch);
}
}
private boolean addSubkeyedItems(ListIterator<AccessLogElement> iterator, List<JsonWrappedElement> elements,
String patternAttribute) {
if (!elements.isEmpty()) {
iterator.add(new StringElement("\"" + patternAttribute + "\": {"));
for (JsonWrappedElement element : elements) {
iterator.add(element);
iterator.add(new CharElement(','));
}
iterator.previous();
iterator.remove();
iterator.add(new StringElement("},"));
return true;
}
return false;
}
@Override
protected AccessLogElement[] createLogElements() {
Map<Character,List<JsonWrappedElement>> subTypeLists = new HashMap<>();
for (Character pattern : SUB_OBJECT_PATTERNS.keySet()) {
subTypeLists.put(pattern, new ArrayList<>());
}
boolean hasSub = false;
List<AccessLogElement> logElements = new ArrayList<>(Arrays.asList(super.createLogElements()));
ListIterator<AccessLogElement> lit = logElements.listIterator();
lit.add(new CharElement('{'));
while (lit.hasNext()) {
AccessLogElement logElement = lit.next();
// remove all other elements, like StringElements
if (!(logElement instanceof JsonWrappedElement)) {
lit.remove();
continue;
}
// Remove items which should be written as
// Json objects and add them later in correct order
JsonWrappedElement wrappedLogElement = (JsonWrappedElement) logElement;
AccessLogElement ale = wrappedLogElement.getDelegate();
if (ale instanceof HeaderElement) {
subTypeLists.get(Character.valueOf('i')).add(wrappedLogElement);
lit.remove();
} else if (ale instanceof ResponseHeaderElement) {
subTypeLists.get(Character.valueOf('o')).add(wrappedLogElement);
lit.remove();
} else if (ale instanceof RequestAttributeElement) {
subTypeLists.get(Character.valueOf('r')).add(wrappedLogElement);
lit.remove();
} else if (ale instanceof SessionAttributeElement) {
subTypeLists.get(Character.valueOf('s')).add(wrappedLogElement);
lit.remove();
} else if (ale instanceof CookieElement) {
subTypeLists.get(Character.valueOf('c')).add(wrappedLogElement);
lit.remove();
} else if (ale instanceof IdentifierElement) {
subTypeLists.get(Character.valueOf('L')).add(wrappedLogElement);
lit.remove();
} else {
// Keep the simple items and add separator
lit.add(new CharElement(','));
}
}
// Add back the items that are output as Json objects
for (Character pattern : SUB_OBJECT_PATTERNS.keySet()) {
if (addSubkeyedItems(lit, subTypeLists.get(pattern), SUB_OBJECT_PATTERNS.get(pattern))) {
hasSub = true;
}
}
// remove last comma (or possibly "},")
lit.previous();
lit.remove();
// Last item was a sub object, close it
if (hasSub) {
lit.add(new StringElement("}}"));
} else {
lit.add(new CharElement('}'));
}
return logElements.toArray(new AccessLogElement[0]);
}
@Override
protected AccessLogElement createAccessLogElement(String name, char pattern) {
AccessLogElement ale = super.createAccessLogElement(name, pattern);
return new JsonWrappedElement(pattern, name, true, ale);
}
@Override
protected AccessLogElement createAccessLogElement(char pattern) {
AccessLogElement ale = super.createAccessLogElement(pattern);
return new JsonWrappedElement(pattern, true, ale);
}
private static class JsonWrappedElement implements AccessLogElement, CachedElement {
private final CharSequence attributeName;
private final boolean quoteValue;
private final AccessLogElement delegate;
private CharSequence escapeJsonString(CharSequence nonEscaped) {
return JSONFilter.escape(nonEscaped);
}
JsonWrappedElement(char pattern, String key, boolean quoteValue, AccessLogElement delegate) {
this.quoteValue = quoteValue;
this.delegate = delegate;
String patternAttribute = PATTERNS.get(Character.valueOf(pattern));
if (patternAttribute == null) {
patternAttribute = "other-" + Character.toString(pattern);
}
if (key != null && !key.isEmpty()) {
if (SUB_OBJECT_PATTERNS.containsKey(Character.valueOf(pattern))) {
this.attributeName = escapeJsonString(key);
} else {
this.attributeName = escapeJsonString(patternAttribute + "-" + key);
}
} else {
this.attributeName = escapeJsonString(patternAttribute);
}
}
JsonWrappedElement(char pattern, boolean quoteValue, AccessLogElement delegate) {
this(pattern, null, quoteValue, delegate);
}
public AccessLogElement getDelegate() {
return delegate;
}
@Override
public void addElement(CharArrayWriter buf, Request request, Response response, long time) {
buf.append('"').append(attributeName).append('"').append(':');
if (quoteValue) {
buf.append('"');
}
delegate.addElement(buf, request, response, time);
if (quoteValue) {
buf.append('"');
}
}
@Override
public void cache(Request request) {
if (delegate instanceof CachedElement) {
((CachedElement) delegate).cache(request);
}
}
}
}
|