Skip to content
Merged
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 @@ -68,8 +68,12 @@ public Stack<Class<?>> getCurrentStackTrace() {
}

public StackTraceElement calcLocation(final String fqcnOfLogger) {
return stackWalker.walk(s -> s.dropWhile(f -> f.getClassName().equals(fqcnOfLogger)).
dropWhile(f -> f.getClassName().equals(fqcnOfLogger)).findFirst()).get().toStackTraceElement();
return stackWalker.walk(
s -> s.dropWhile(f -> !f.getClassName().equals(fqcnOfLogger)) // drop the top frames until we reach the logger
.dropWhile(f -> f.getClassName().equals(fqcnOfLogger)) // drop the logger frames
.findFirst())
.get()
.toStackTraceElement();
}

public StackTraceElement getStackTraceElement(final int depth) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
*/
package org.apache.logging.log4j.util;

import java.util.Stack;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.ParentRunner;
import static org.junit.Assert.*;

import java.util.Stack;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

@RunWith(BlockJUnit4ClassRunner.class)
public class StackLocatorTest {
Expand Down Expand Up @@ -91,6 +94,47 @@ public void testLocateClass() {
assertEquals("Incorrect class", this.getClass(), clazz);
}

private final class Foo {

private StackTraceElement foo() {
return new Bar().bar();
}

}

private final class Bar {

private StackTraceElement bar() {
return baz();
}

private StackTraceElement baz() {
return quux();
}

}

private StackTraceElement quux() {
return stackLocator.calcLocation("org.apache.logging.log4j.util.StackLocatorTest$Bar");
}

@Test
public void testCalcLocation() {
/*
* We are setting up a stack trace that looks like:
* - org.apache.logging.log4j.util.StackLocatorTest#quux(line:118)
* - org.apache.logging.log4j.util.StackLocatorTest$Bar#baz(line:112)
* - org.apache.logging.log4j.util.StackLocatorTest$Bar#bar(line:108)
* - org.apache.logging.log4j.util.StackLocatorTest$Foo(line:100)
*
* We are pretending that org.apache.logging.log4j.util.StackLocatorTest$Bar is the logging class, and
* org.apache.logging.log4j.util.StackLocatorTest$Foo is where the log line emanated.
*/
final StackTraceElement element = new Foo().foo();
assertEquals("org.apache.logging.log4j.util.StackLocatorTest$Foo", element.getClassName());
assertEquals(100, element.getLineNumber());
}

class ClassLocator {

public Class<?> locateClass() {
Expand Down