Class LogFormatterJson
java.lang.Object
java.util.logging.Formatter
org.nanonative.nano.helper.logger.logic.LogFormatterJson
A log formatter that outputs log records in JSON format.
This formatter structures log messages into JSON objects, which is beneficial for systems that ingest log data for analysis, allowing for easy parsing and structured querying of log data.
Usage Example:
logger.info(() -> throwable, "Processed records - success: [{}], failure: [%s], ignored; [{2}]", successCount, failureCount, ignoreCount, Map.of("username", "yuna"));
In this example, 'successCount' replaces the first '{}' placeholder, 'failureCount' replaces the '%s' placeholder and 'ignoreCount' replaces the last [{2}] placeholder.
The formatter will convert the log into a JSON line.
The map's keys and values becoming part of the JSON structure.
A key value map is not really needed as the keys and values from the messages itself becomes a part of the JSON structure as well. This makes it easier to switch between console and json logging.
Additionally, it supports automatic key-value extraction from the log message itself, enabling inline parameterization. The extracted keys and values are also included in the JSON output.
The formatter handles exceptions by appending a "error" field with the exception message to the JSON log entry.
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddJsonEntries(Map<String, String> jsonMap, Object[] params) Adds additional key-value pairs to the map.protected voidExtracts key-value pairs from the message and stores them in a map.Formats a log record into a JSON string.protected StringjsonEscape(Object value) Escapes special characters for JSON compatibility.protected voidAdds escaped and converted key-value pairs to the map.Methods inherited from class java.util.logging.Formatter
formatMessage, getHead, getTail
-
Field Details
-
dateFormat
-
MESSAGE_KEY_VALUE_PATTERN
-
-
Constructor Details
-
LogFormatterJson
public LogFormatterJson()
-
-
Method Details
-
format
Formats a log record into a JSON string. -
extractKeyValuesFromMessage
protected void extractKeyValuesFromMessage(Map<String, String> jsonMap, String message, Object[] params) Extracts key-value pairs from the message and stores them in a map.- Parameters:
jsonMap- The map to store the key-value pairs.message- The log message.params- The parameters for the log message.
-
addJsonEntries
Adds additional key-value pairs to the map.- Parameters:
jsonMap- The map to store the key-value pairs.params- The parameters for the log message.
-
putEntry
Adds escaped and converted key-value pairs to the map.- Parameters:
jsonMap- The map to store the key-value pairs.key- keyvalue- value
-
jsonEscape
Escapes special characters for JSON compatibility.- Parameters:
value- The object to escape.- Returns:
- The escaped string.
-