Catch RuntimeExceptions in Java application and se

2019-04-13 21:09发布

I'm starting my app on Linux server with a command like this

/usr/local/bin/jsvc \
    -home /usr/local/jdk1.8.0_111 \
    -cp /opt/myapp/myapp.jar:/opt/myapp/lib/* \
    -user myappuser \
    -outfile /opt/myapp/out.log \
    -errfile /opt/myapp/error.log \
    -pidfile /opt/myapp/myapp.pid \
    com.example.MyApp

I'm using log4j for logging in my app and it has own configuration described in log4j.properties which is located inside myapp.jar.

I want to be able to catch any exception which happens in the app and to send it to me via email. I have configured org.apache.log4j.net.SMTPAppender in log4j.properties for that purpose.

But currently RuntimeException, like NullPointerException are just printed to stderr which jsvc redirects to error.log without applying log4j formatting pattern.

Is it possible or should I run the app without jsvc wrapper like

nohup java -jar /opt/myapp/myapp.jar &

or is there better solution?

1条回答
我命由我不由天
2楼-- · 2019-04-13 21:38

Answering myself. Just set default UncaughtExceptionHandler at the beginning of your code entry point

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.error(null, e));
    }

}

log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/opt/myapp/myapp.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %m%n

# SMTP 
log4j.appender.email=org.apache.log4j.net.SMTPAppender
log4j.appender.email.SMTPHost=yoursmtp.example.com
log4j.appender.email.SMTPUsername=youuser@yoursmtp.example.com
log4j.appender.email.SMTPPassword=yourpassword
log4j.appender.email.From=youuser@yoursmtp.example.com
log4j.appender.email.To=youremail@example.com
log4j.appender.email.Subject=An error has happened
log4j.appender.email.BufferSize=1
log4j.appender.email.layout=org.apache.log4j.PatternLayout
log4j.appender.email.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1}:%L - %m%n
log4j.appender.email.Threshold = ERROR
查看更多
登录 后发表回答