Add method to format message to LogRecord. PiperOrigin-RevId: 373721268
diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java index 723d3cf..5de65e3 100644 --- a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java
@@ -379,6 +379,10 @@ this.message = message; } + public String getFormattedMessage() { + return lenientFormat(message, parameters); + } + /** * Get the parameters to the log message. * @@ -604,4 +608,58 @@ cname.startsWith("java.util.logging.LoggingProxyImpl") || cname.startsWith("sun.util.logging.")); } + + public static String lenientFormat(String template, Object... args) { + + template = String.valueOf(template); // null -> "null" + + if (args == null) { + args = new Object[] {"(Object[])null"}; + } else { + for (int i = 0; i < args.length; i++) { + args[i] = lenientToString(args[i]); + } + } + + // start substituting the arguments into the '%s' placeholders + StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); + int templateStart = 0; + int i = 0; + while (i < args.length) { + int placeholderStart = template.indexOf("%s", templateStart); + if (placeholderStart == -1) { + break; + } + builder.append(template, templateStart, placeholderStart); + builder.append(args[i++]); + templateStart = placeholderStart + 2; + } + builder.append(template, templateStart, template.length()); + + // if we run out of placeholders, append the extra args in square braces + if (i < args.length) { + builder.append(" ["); + builder.append(args[i++]); + while (i < args.length) { + builder.append(", "); + builder.append(args[i++]); + } + builder.append(']'); + } + return builder.toString(); + } + + private static String lenientToString(Object o) { + if (o == null) { + return "null"; + } + try { + return o.toString(); + } catch (Exception e) { + // Default toString() behavior - see Object.toString() + String objectToString = o.getClass().getName() + '@' + + Integer.toHexString(System.identityHashCode(o)); + return "<" + objectToString + " threw " + e.getClass().getName() + ">"; + } + } }