Class KeyValueFormatter

  • All Implemented Interfaces:
    FloggerMetadataKey.KeyValueHandler

    public final class KeyValueFormatter
    extends Object
    implements FloggerMetadataKey.KeyValueHandler
    Formats key/value pairs as a human readable string on the end of log statements. The format is:
       Log Message PREFIX[ key1=value1 key2=value2 ]
     
    or
       Multi line
       Log Message
       PREFIX[ key1=value1 key2=value2 ]
     
    Note that:
    • Key/value pairs are appended in the order they are handled.
    • If no key/value pairs are handled, the log message is unchanged (no prefix is added).
    • Keys can be repeated.
    • Key labels do not need quoting.
    • String-like values are properly quoted and escaped (e.g. \", \\, \n, \t)
    • Unsafe control characters in string-like values are replaced by U+FFFD (�).
    • All key/value pairs are on the "same line" of the log message.
    The result is that this string should be fully reparsable (with the exception of replaced unsafe characters) and easily searchable by text based tools such as "grep".
    See Also:
    Original Java code of Google Flogger
    • Constructor Detail

      • KeyValueFormatter

        public KeyValueFormatter​(String prefix,
                                 String suffix,
                                 StringBuilder out)
        Creates a formatter using the given prefix to append key/value pairs to the current log message.
    • Method Detail

      • appendJsonFormattedKeyAndValue

        public static void appendJsonFormattedKeyAndValue​(String label,
                                                          Object value,
                                                          StringBuilder out)
        Helper method to emit metadata key/value pairs in a format consistent with JSON. String values which need to be quoted are JSON escaped, while other values are appended without quoting or escaping. Labels are expected to be JSON "safe", and are never quoted. This format is compatible with various "lightweight" JSON representations.
      • done

        public void done()
        Terminates handling of key/value pairs, leaving the originally supplied buffer modified.