-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathLogFmtLineBuilder.java
More file actions
63 lines (51 loc) · 1.75 KB
/
Copy pathLogFmtLineBuilder.java
File metadata and controls
63 lines (51 loc) · 1.75 KB
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
package com.uid2.shared.util;
import io.vertx.core.json.JsonObject;
import java.util.Map;
public class LogFmtLineBuilder {
private final StringBuilder stringBuilder;
public LogFmtLineBuilder() {
this.stringBuilder = new StringBuilder();
}
private String escape(String value) {
if (value == null) {
return "null";
}
if (value.contains(" ") || value.contains("\"") || value.contains("=") || value.contains("\n") ||
value.contains("\r") || value.contains("\t") || value.contains("\\")) {
return "\"" + value.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t") + "\"";
}
return value;
}
public LogFmtLineBuilder with(String key, String value) {
if (!stringBuilder.isEmpty()) {
stringBuilder.append(" ");
}
stringBuilder.append(key).append("=").append(escape(value));
return this;
}
public LogFmtLineBuilder with(Map<String, String> map) {
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
with(entry.getKey(), entry.getValue());
}
}
return this;
}
public LogFmtLineBuilder with(String key, int value) {
return with(key, String.valueOf(value));
}
// Only supports one level of nesting
public LogFmtLineBuilder with(String key, JsonObject obj) {
for (String objKey : obj.fieldNames()) {
with(key+ "." + objKey, obj.getString(objKey));
}
return this;
}
public String build() {
return stringBuilder.toString();
}
}