Catch RuntimeExceptions in Java application and send them via email

假装没事ソ 提交于 2019-12-06 09:23:27

问题


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:


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


来源:https://stackoverflow.com/questions/42434527/catch-runtimeexceptions-in-java-application-and-send-them-via-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!