1

Is it a good idea to print method name in the log by defining method name as a string in the production like below?

private void foo() {
    String methogTag = "foo"; // here defining method name
    int updateCount = // db update operation
    log.info("{} : {} record/s are updated", methogTag, updateCount);

    int deleteCount = // db delete operation
    log.info("{} : {} record/s are deleted", methogTag, deleteCount);
}

log output:

2019-04-22 13:24:41.572 ClazzName - foo : 20 record/s are updated
2019-04-22 13:24:41.600 ClazzName - foo : 12 record/s are deleted

We can get method name printed in logs using %M in log4j pattern layout.

pattern layout:

%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%t] %c{3.}%M - %msg%n

And there is a warning in the log4j documentation

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

Or, is there any alternative way to get the method name in the loggers without any memory overhead?

Thanks.

1 Answers1

-1

There is a way in Junit to get method name without storing it in any Variable.

Junit5 TestInfo Class

If I am correct you are not writing Test cases,just some logic Instead of storing the method name,you can get it using

Thread.currentThread()
      .getStackTrace()[1]
      .getMethodName();

But why to store each and every method name being executed in log files,the best practice would be to print the stacktrace when ever any exception occurs So in the stackTrace not only you can get the line number in the method where the exception occured but also the flow,as to how the method was executed.

Ayush Goyal
  • 63
  • 1
  • 2
  • 11
  • Thanks @Ayush Goyal - Yes, I'm not writing Test cases. For exeptions it is okay to print stacktrace. But for info (like log output in question), won't it be very expensive at runtime, and hence slow down performance by getting stacktrace and method name? – Harish Thatikonda Apr 22 '19 at 11:07
  • Yes it will be,so the best practice would be to write something like `log.info(updateCount+" records are updated");` So anyone can easily see what the course of action was and in case of exception you can always log full stacktrace to the files – Ayush Goyal Apr 22 '19 at 11:58