3

how does my Java logger (say logback) find the line number of my code?

Is this a performance issue in a high performance system to include the file line number?

Does it need to throw an exception and analyse the stack trace to do this or is there another trick to this?

thanks

CodingHero
  • 2,865
  • 6
  • 29
  • 42

2 Answers2

5

Line numbers are compiled into the .class files and getting them is certainly more work than not doing so.

You can get a stacktrace without throwing an exception via Thread#getStackTrace() but that should have roughly the same cost as creating an exception (you don't need to throw and catch it).

Collecting the information can be quite expensive as mentioned in How Expensive is Thread.getStackTrace()?

But excessive logging alone can already slow down the system drastically.

Is this a performance issue in a high performance system to include the file line number?

You should test it. If it is not already a performance issue without line numbers, chances are that it is no issue with. It all depends on where and how often you log.


The documentation also mentions line numbers

Generating the line number information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue.

Community
  • 1
  • 1
zapl
  • 63,179
  • 10
  • 123
  • 154
1

how does my Java logger (say logback) find the line number of my code?

You can read the code for yourself. It is available online in various places.

Is this a performance issue in a high performance system to include the file line number?

Yes it is, if you make a lot of logger.log calls (or equivalent). And the documentation for both Log4j and Logback say this.

Does it need to throw an exception and analyse the stack trace to do this or is there another trick to this?

My understanding is that this is the only practical way for application code to do this.

(You could hypothetically reuse an existing exception object and call fillInStackTrace() each time you wanted to capture the stack frames. However, the performance benefit would be miniscule, especially once you have dealt with multi-threading issues.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216