Override Logback error output

前端 未结 1 1716
野性不改
野性不改 2021-02-14 09:37

In my custom exception class I\'ve overridden toString():

@Override
public String toString() {
    final String msg = getLocalizedMessage();

    //         


        
1条回答
  •  不知归路
    2021-02-14 10:22

    A quick and dirty way is this: logger.warn("your_message_here \n{}", err.toString());

    A better way would be to write your own custom conversion specifier (see logback manual so that the custom error handling is abstracted from your application code, and you can configure it's use through a custom conversion word in your logback.xml.

    Here's a simple example that will do what you're after:

    package com.example.logging;
    
    import ch.qos.logback.classic.pattern.ClassicConverter;
    import ch.qos.logback.classic.spi.ILoggingEvent;
    import ch.qos.logback.classic.spi.IThrowableProxy;
    import ch.qos.logback.classic.spi.ThrowableProxy;
    
    /**
     * Simple exception converter.
     *
     */
    public class MyExceptionConverter extends ClassicConverter {
        /* (non-Javadoc)
         * @see ch.qos.logback.core.pattern.Converter#convert(java.lang.Object)
         */
        @Override
        public String convert(ILoggingEvent event) {
            IThrowableProxy itp = event.getThrowableProxy();
            if (itp instanceof ThrowableProxy) {
                ThrowableProxy tp = (ThrowableProxy)itp;
                return tp.getThrowable().toString();
            }
    
            return "";
        }
    }
    

    Then in your logback.xml you'll need to reference it like this:

      
    

    And then use %myCon in an encoder pattern like this:

    
        %d{dd MMM yyyy HH:mm:ss.SSS} %logger{0}: %myCon %nopex%n
    
    

    Note that adding %nopex stops the usual exception handling

    0 讨论(0)
提交回复
热议问题