Skip to content

Fix issue #2363: Extract Throwable should be irrelevant to the count of patternAnalysis #2368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.apache.logging.log4j.message;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.math.BigDecimal;
import java.util.List;
Expand Down Expand Up @@ -159,6 +160,17 @@ void testSafeWithMutableParams() { // LOG4J2-763
assertThat(after).isEqualTo("Test message XYZ").as("Should not change after rendered once");
}

@Test
public void testException() {
final String testMsg = "Test message {}, exception is {}";
final ParameterizedMessage msg = new ParameterizedMessage(testMsg, "Apache", new NullPointerException());
final String result = msg.getFormattedMessage();
final String expected = "Test message Apache, exception is ";
assertThat(result).contains(expected);
final Throwable t = msg.getThrowable();
assertNotNull(t, "No Throwable");
}

static Stream<Object> testSerializable() {
@SuppressWarnings("EqualsHashCode")
class NonSerializable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,19 +144,19 @@ public ParameterizedMessage(final String pattern, final Object[] args, final Thr
this.args = args;
this.pattern = pattern;
this.patternAnalysis = analyzePattern(pattern, args != null ? args.length : 0);
this.throwable = determineThrowable(throwable, this.args, patternAnalysis);
this.throwable = determineThrowable(throwable, this.args);
}

private static Throwable determineThrowable(
final Throwable throwable, final Object[] args, final MessagePatternAnalysis analysis) {
private static Throwable determineThrowable(final Throwable throwable, final Object[] args) {

// Short-circuit if an explicit `Throwable` is provided
if (throwable != null) {
return throwable;
}

// If the last `Throwable` argument is not consumed in the pattern, use that
if (args != null && args.length > analysis.placeholderCount) {
// Fix issue #2363: Extract Throwable should be irrelevant to the count of patternAnalysis
if (args != null && args.length > 0) {
Object lastArg = args[args.length - 1];
if (lastArg instanceof Throwable) {
return (Throwable) lastArg;
Expand Down