Explain Codes LogoExplain Codes Logo

How can we print line numbers to the log in Java

java
logging
debugging
performance-cost
Anton ShumikhinbyAnton Shumikhin·Feb 11, 2025
TLDR

Activate line numbers in your logs with the %L pattern token in your Log4j or SLF4J configuration. Use the regular logging methods like logger.info, line numbers will now show up automatically.

Logger logger = LogManager.getLogger(LogExample.class); logger.info("Message with line number"); //Line numbers will appear like magic

Put this in your log4j2.xml file:

<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n"/>

The magical %L is where line numbers appear in your log.

Understanding line numbers in logs

Line numbers in logs give you a treasure map that takes you straight to the source of the problem. Let's dig deeper.

Using StackTrace for line numbers

If you're not using logging frameworks, guess what? You can still track the line numbers using StackTrace. Surprise!

int lineNumber = Thread.currentThread().getStackTrace()[2].getLineNumber(); logger.info("This line is from brain of Oracle (no pun), line number: " + lineNumber); // Alright, a little bit of pun

Save the day with a custom Logger

For a consistent approach, you can create a custom logger that attaches line numbers before each log message:

public class LineNumberLogger { // Your trusty sidekick private static final Logger logger = LogManager.getLogger(LineNumberLogger.class); public static void info(String message) { StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; // Doing all the heavy lifting logger.info(ste.getFileName() + ":" + ste.getLineNumber() + " - " + message); } // Now just redux this for debug, warn, error, etc. }

Call LineNumberLogger.info() and you're all set with your class, method, and line number.

Control the level of detail in your logs

You might not always want the Mariana Trench level of detail in your logs. Use a boolean flag to toggle between chatty and polite logs:

private static final boolean detailedLogs = true; // Sometimes, less is more if(detailedLogs) { LineNumberLogger.info("Chatty log message"); // It's like Yelp for logs }

Do's and Don'ts of line numbers

Line numbers save you time by revealing the exact scene of the crime, especially during debugging or postmortem analysis.

The good...

Adding line numbers programmatically reduces the risk of human error and lightens the maintenance burden. These line specific logs also bring the debugging game to a new level of simplicity.

The bad...

But beware! In highly sensitive and performance-critical environments, line numbers might be omitted to save on performance cost.

The ugly...

There can still be readability nightmares. Despite systematic inclusion, logs without meaningful messages are as helpful as a chocolate teapot.