io.convergence_platform.services.observability.serializers.JsonLogSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of service-lib Show documentation
Show all versions of service-lib Show documentation
Holds the common functionality needed by all Convergence Platform-based services written in Java.
The newest version!
package io.convergence_platform.services.observability.serializers;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.convergence_platform.common.annotations.SkipFieldLogging;
import io.convergence_platform.common.helpers.JsonHelper;
import io.convergence_platform.services.observability.ILogSerializer;
import io.convergence_platform.services.observability.RequestLog;
import java.io.FileOutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;
public class JsonLogSerializer implements ILogSerializer {
private final int FIELD_LENGTH = 25;
private final String logFolder;
private final boolean production;
public JsonLogSerializer(String logFolder, boolean production) {
this.logFolder = logFolder;
this.production = production;
}
@Override
public void save(RequestLog requestLog) {
removeJwtSignature(requestLog);
Map requestAsMap = (Map) convertRequestToMap(requestLog);
requestAsMap.put("service_language", "java");
requestAsMap.put("template_version", "?");
String json = null;
if (production) {
json = JsonHelper.asJsonString(requestAsMap);
} else {
json = JsonHelper.asJsonStringPretty(requestAsMap);
}
writeAllBytes(logFolder + "/" + requestLog.requestIdentifier.toString() + ".crl", json.getBytes());
}
public Object convertRequestToMap(Object obj) {
Object result = null;
if (obj instanceof Map) {
Map o = (Map) obj;
Map map = new HashMap<>();
for (String key : o.keySet()) {
map.put(key, convertRequestToMap(o.get(key)));
}
result = map;
} else if (obj == null) {
result = null;
} else if (valueSupportedByJson(obj)) {
result = obj;
} else if (obj instanceof List) {
List list = new ArrayList();
for (Object o : (List) obj) {
list.add(convertRequestToMap(o));
}
result = list;
} else if (obj.getClass().isArray()) {
List list = new ArrayList();
for (int i = 0; i < Array.getLength(obj); i++) {
list.add(convertRequestToMap(Array.get(obj, i)));
}
result = list;
} else {
Field[] fields = obj.getClass().getFields();
Map map = new HashMap<>();
for (Field field : fields) {
JsonProperty annotation = field.getAnnotation(JsonProperty.class);
if (annotation != null) {
SkipFieldLogging skip = field.getAnnotation(SkipFieldLogging.class);
if (skip != null) {
map.put(annotation.value(), "***********");
} else {
try {
map.put(annotation.value(), convertRequestToMap(field.get(obj)));
} catch (IllegalAccessException e) {
map.put(annotation.value(), null);
}
}
}
}
result = map;
}
return result;
/*
if isinstance(obj, dict):
return {str(key): convert_object_to_dict(item) for key, item in obj.items()}
elif obj is None:
return None
elif isinstance(obj, int) or isinstance(obj, float):
return obj
elif not hasattr(obj, "__dict__"):
return str(obj)
result = {}
skip_field = '_SKIP_LOGGING_FIELDS'
secret_fields = getattr(obj, skip_field) if hasattr(obj, skip_field) else []
for key, val in obj.__dict__.items():
if key.startswith("_"):
continue
if isinstance(val, list):
element = []
for item in val:
element.append(convert_object_to_dict(item))
elif isinstance(val, set) or isinstance(val, tuple):
element = []
val = list(val)
for item in val:
element.append(convert_object_to_dict(item))
else:
element = convert_object_to_dict(val)
result[key] = element
for field in secret_fields:
result[field] = '***********'
return result
*/
}
private boolean valueSupportedByJson(Object obj) {
return (obj instanceof Boolean)
|| (obj instanceof Long)
|| (obj instanceof Integer)
|| (obj instanceof String)
|| (obj instanceof Double)
|| (obj instanceof Byte)
|| (obj instanceof Float)
|| (obj instanceof Short)
;
}
private void removeJwtSignature(RequestLog requestLog) {
if (requestLog.headers.containsKey("authorization")) {
String auth = requestLog.headers.get("authorization");
auth = auth.substring(0, auth.lastIndexOf(".") + 1) + "***********";
requestLog.headers.put("authorization", auth);
}
}
private void addJsonMap(StringBuilder result, Map params, String indent) {
for (String key : params.keySet()) {
Object value = params.get(key);
if (value instanceof Map, ?>) {
result.append("\n").append(indent).append(key).append(":");
addJsonMap(result, (Map) value, indent + " ");
} else if (value instanceof List>) {
result.append("\n").append(indent).append(key).append(":");
List list = (List) value;
int ii = 0;
for (Object item : list) {
ii++;
if (item instanceof Map, ?>) {
result.append(indent).append("[").append(ii).append("]\n");
addJsonMap(result, (Map) item, indent + " ");
} else {
result.append("\n").append(pad(indent + " [" + ii + "]" + ": ", FIELD_LENGTH)).append(String.valueOf(item));
}
}
} else {
result.append("\n").append(pad(indent + key + ":", FIELD_LENGTH)).append(String.valueOf(value));
}
}
}
private String pad(String value, int length) {
StringBuilder result = new StringBuilder();
result.append(value);
while (result.length() < length) {
result.append(" ");
}
return result.toString();
}
public static void writeAllBytes(String path, byte[] content) {
try {
FileOutputStream fs = new FileOutputStream(path);
fs.write(content);
fs.flush();
fs.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}