Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the correct posture for recording Java exception information in the log?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to record the correct posture of Java abnormal information in the log, the content is very detailed, interested friends can refer to, I hope it can be helpful to you!

Problems encountered in logging Java exception information

Today, I encountered an online BUG that failed to perform a form submission, but did not see any exception information in the program log.

When I found in the Review source code, I only output e.getMessage () when catch to an exception, as shown below:

Logger.error ("error: {}, {}", params, e.getMessage ())

No information is seen in the log, indicating that the return value of e.getMessage () is an empty string.

Cause analysis

Let's first take a look at the exception class diagram in Java:

So when will this property be assigned? trace back to the source code and find that the property will only be assigned in the Throwable constructor.

Public Throwable () {/ / does not assign fillInStackTrace () to the detailMessage property in the default constructor;} public Throwable (String message) {fillInStackTrace (); / / directly assigns parameters to detailMessage detailMessage = message;} public Throwable (String message, Throwable cause) {fillInStackTrace (); / / directly assigns parameters to detailMessage detailMessage = message; this.cause = cause;} public Throwable (Throwable cause) {fillInStackTrace () / / assign detailMessage = (cause==null?) to detailMessage when the Throwable object passed in is not empty. Null: cause.toString (); this.cause = cause;} protected Throwable (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {if (writableStackTrace) {fillInStackTrace ();} else {stackTrace = null;} / / directly assign the parameter to detailMessage detailMessage = message; this.cause = cause If (! enableSuppression) suppressedExceptions = null;}

Obviously, you can see from the source code that the detailMessage attribute is not assigned in the default constructor of Throwable.

That is, when the exception object is instantiated through the default constructor, or when the message passed in when instantiated is an empty string, the return value is empty when the getMessage () method is called, which is the case I encountered.

Therefore, do not simply use the getMessage () method to get exception information in the program log (when the return value is empty, it is not conducive to troubleshooting).

The right thing to do

In Java development, the commonly used logging framework and components are usually: slf4j,log4j and logback, their relationship can be described as: slf4j provides a unified logging API, and gives the specific logging implementation to log4j and logback.

Org.slf4j slf4j-api 1.7.25 ch.qos.logback logback-core 1.2.3 ch.qos.logback logback-classic 1.2.3

The above configuration takes the integration of slf4j and logback as an example to add the corresponding logback configuration file (logback.xml):

Date level [% thread]% logger {10} [% file:%line]% msg%n test.log% date% level [% thread]% logger {10} [% file:%line]% msg%n

Log through the log API provided by slf4j in Java:

Import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class Test {private static final Logger logger = LoggerFactory.getLogger (Test.class);}

When we need to output exception information in the program log, we should pass in the exception object directly instead of simply getting the output exception information through the getMessage () method of the exception object.

Public void test () {try {/ / instantiate the exception object throw new NullPointerException () using the default constructor;} catch (Exception e) {/ / pass the exception object directly into the log interface and save the exception information to the log file logger.error ("error: {}", e.getMessage (), e); e.printStackTrace ();}}

The following is a fragment of exception information saved to the log file:

2019-06-20 20 ERROR [http-nio-8090-exec-1] o.c.s.f.c.TestExceptionController [TestExceptionController.java:26] error: null # when an exception object is instantiated with the default construction parameter The getMessage () method returns an empty object # the following is the specific exception stack information java.lang.NullPointerException: null at org.chench.springboot.falsework.controller.TestExceptionController.test (TestExceptionController.java:24) ~ [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0 (NativeMethod) ~ [na:1.8.0_181] at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) ~ [na:1.8.0_181] at sun.reflect.DelegatingMethodAccessorImpl.invoke 5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:102) [spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod (RequestMappingHandlerAdapter.java:877) [spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework .web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:783) [spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle (AbstractHandlerMethodAdapter.java:87) [spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet.java:991) [spring-webmvc-5.0 Where does e.printStackTrace () print?

E.printStackTrace () in catch will print to the console

2. What is the printed content of e.printStackTrace ()? import org.apache.logging.log4j.Logger; public class ExceptionTest {private static final Logger logger=LogManager.getLogger (); public void test () {try {int item1Accord 0;} catch (Exception e) {e.printStackTrace ();}} public static void main (String [] args) {ExceptionTest test= new ExceptionTest () Test.test ();}}

The output is as follows:

Java.lang.ArithmeticException: / by zero

At myProject.ExceptionTest.test (ExceptionTest.java:10)

At myProject.ExceptionTest.main (ExceptionTest.java:18)

It can be seen that e.printStackTrace () prints the specific information of the error, that is, the location of the error, so it is easy to find the source of the error.

3. What should I do if I print the information of e.printStackTrace () in the log?

See the following code:

Package myProject; import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger; public class ExceptionTest {private static final Logger logger=LogManager.getLogger (); public void test () {try {int iTunes 1 + 0;} catch (Exception e) {logger.error (e);}} public static void main (String [] args) {ExceptionTest test= new ExceptionTest () Test.test ();}}

Print the log with logger.error (e);, and the output is as follows:

19RV 17JV 39.753 [main] ERROR myProject.ExceptionTest-java.lang.ArithmeticException: / by zero

It can be seen that the log printed in this way has only a rough error message and does not indicate the location of the code where the error is reported, so it is not easy to find the error. Using logger.error (e.getMessage ()); also outputs this approximate error message.

Goodbye to the following code:

Package myProject; import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger; public class ExceptionTest {private static final Logger logger=LogManager.getLogger (); public void test () {try {int iTunes 1 + 0;} catch (Exception e) {logger.error ("ExceptionTest Exception:", e) }} public static void main (String [] args) {ExceptionTest test= new ExceptionTest (); test.test ();}}

With logger.error ("ExceptionTest Exception:", e);, the output is as follows:

920 main 32. 948 [main] ERROR myProject.ExceptionTest-ExceptionTest Exception:

Java.lang.ArithmeticException: / by zero

At myProject.ExceptionTest.test (ExceptionTest.java:10) [classes/:?]

At myProject.ExceptionTest.main (ExceptionTest.java:18) [classes/:?]

This is roughly the same as what e.printStackTrace () prints. However, it is best to use the logger.error (e.getMessage (), e) method to view the detailed results of the exception in the log.

About how to record the correct posture of Java abnormal information in the log is shared here. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report