diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LoggingEventBuilder.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LoggingEventBuilder.java index fbfc0821e9dc8..5fa0d2ba84628 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LoggingEventBuilder.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LoggingEventBuilder.java @@ -369,11 +369,11 @@ private void performLogging(LogLevel logLevel, String format, Object... args) { * Serializes passed map to string containing valid JSON fragment: * e.g. "k1":"v1","k2":"v2", properly escaped and without trailing comma. * - * Does not support custom or complex object serialization, uses {@code toString()} on them. + * For complex object serialization, it calls {@code toString()} guarded with null check. * * @param context to serialize. * - * @returns Serialized JSON fragment or empty string. + * @returns Serialized JSON fragment or an empty string. */ static String writeJsonFragment(Map context) { if (CoreUtils.isNullOrEmpty(context)) { @@ -399,13 +399,9 @@ private static StringBuilder writeKeyAndValue(String key, Object value, StringBu return formatter.append("null"); } - // LoggingEventBuilder only populates primitives and Strings - if (value instanceof Boolean - || value instanceof Integer - || value instanceof Long - || value instanceof Byte) { - JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); - return formatter; + if (isPrimitive(value)) { + JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); + return formatter; } formatter.append("\""); @@ -413,6 +409,26 @@ private static StringBuilder writeKeyAndValue(String key, Object value, StringBu return formatter.append("\""); } + /** + * Returns true if the value is an instance of a primitive type and false otherwise. + */ + private static boolean isPrimitive(Object value) { + // most of the time values are strings + if (value instanceof String) { + return false; + } + + if (value instanceof Boolean + || value instanceof Integer + || value instanceof Long + || value instanceof Byte + || value instanceof Double + || value instanceof Float) { + return true; + } + + return false; + } private static final class ContextKeyValuePair { private final String key;