Skip to content

Commit a0040eb

Browse files
committed
Print RuntimeException raised by StructuredLogFormatter::format to system err
Before this commit, runtime exception is swallowed silently. For example, if two `StructuredLoggingJsonMembersCustomizer` add same key, exception is printed now: ``` Exception in thread "main" java.lang.IllegalStateException: The name 'test' has already been written at org.springframework.util.Assert.state(Assert.java:101) at org.springframework.boot.json.JsonValueWriter.writePair(JsonValueWriter.java:228) at org.springframework.boot.json.JsonValueWriter.write(JsonValueWriter.java:83) at org.springframework.boot.json.JsonWriter$Member.write(JsonWriter.java:650) at org.springframework.boot.json.JsonWriter$Members.write(JsonWriter.java:339) ```
1 parent 3ddfd62 commit a0040eb

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/structured/JsonWriterStructuredLogFormatter.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
*
3030
* @param <E> the log event type
3131
* @author Phillip Webb
32+
* @author Yanming Zhou
3233
* @since 3.4.0
3334
*/
3435
public abstract class JsonWriterStructuredLogFormatter<E> implements StructuredLogFormatter<E> {
@@ -68,12 +69,26 @@ protected JsonWriterStructuredLogFormatter(JsonWriter<E> jsonWriter) {
6869

6970
@Override
7071
public String format(E event) {
71-
return this.jsonWriter.writeToString(event);
72+
try {
73+
return this.jsonWriter.writeToString(event);
74+
}
75+
catch(RuntimeException ex) {
76+
// exception can not be logged due to "Chicken-and-egg" problem
77+
ex.printStackTrace(System.err);
78+
throw ex;
79+
}
7280
}
7381

7482
@Override
7583
public byte[] formatAsBytes(E event, Charset charset) {
76-
return this.jsonWriter.write(event).toByteArray(charset);
84+
try {
85+
return this.jsonWriter.write(event).toByteArray(charset);
86+
}
87+
catch(RuntimeException ex) {
88+
// exception can not be logged due to "Chicken-and-egg" problem
89+
ex.printStackTrace(System.err);
90+
throw ex;
91+
}
7792
}
7893

7994
}

0 commit comments

Comments
 (0)