简体   繁体   中英

Is it bad practice to use method name as a parameter to logger when printing logs?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM