diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java index ac96a1736fb..0e990894c0f 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java @@ -459,7 +459,7 @@ private static boolean appendDate(final Object o, final StringBuilder str) { if (!(o instanceof Date)) { return false; } - str.append(DATE_FORMATTER.format(((Date) o).toInstant())); + DATE_FORMATTER.formatTo(((Date) o).toInstant(), str); return true; } diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/status/StatusData.java b/log4j-api/src/main/java/org/apache/logging/log4j/status/StatusData.java index a56cf0e9f99..337224459ac 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/status/StatusData.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/status/StatusData.java @@ -38,7 +38,6 @@ public class StatusData implements Serializable { private final Instant instant; - @Nullable private final DateTimeFormatter instantFormatter; @Nullable @@ -79,7 +78,8 @@ public StatusData( @Nullable final String threadName, @Nullable final DateTimeFormatter instantFormatter, final Instant instant) { - this.instantFormatter = instantFormatter; + // DateTimeFormatter.ISO_INSTANT is the default used in instant.toString() + this.instantFormatter = instantFormatter != null ? instantFormatter : DateTimeFormatter.ISO_INSTANT; this.instant = instant; this.caller = caller; this.level = requireNonNull(level, "level"); @@ -167,9 +167,7 @@ public Throwable getThrowable() { @SuppressWarnings("DefaultCharset") public String getFormattedStatus() { final StringBuilder sb = new StringBuilder(); - final String formattedInstant = - instantFormatter != null ? instantFormatter.format(instant) : instant.toString(); - sb.append(formattedInstant); + instantFormatter.formatTo(instant, sb); sb.append(SPACE); sb.append(getThreadName()); sb.append(SPACE); diff --git a/src/changelog/.2.x.x/2515_datetimeformatter_formatto.xml b/src/changelog/.2.x.x/2515_datetimeformatter_formatto.xml new file mode 100644 index 00000000000..b8cc41d1b2d --- /dev/null +++ b/src/changelog/.2.x.x/2515_datetimeformatter_formatto.xml @@ -0,0 +1,8 @@ + + + + Replace some usages of `DateTimeFormatter#toString()` with `DateTimeFormatter#formatTo(StringBuilder)` to cut down on allocations +