2

我正在使用这样的命令在 Linux 服务器上启动我的应用程序

/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

log4j用于登录我的应用程序,它有自己的配置,log4j.properties其中描述位于myapp.jar.

我希望能够捕获应用程序中发生的任何异常并通过电子邮件将其发送给我。我已经为此目的进行了配置org.apache.log4j.net.SMTPAppenderlog4j.properties

但目前RuntimeException,likeNullPointerException只是打印到重定向到的,stderr而不应用格式化模式。jsvcerror.loglog4j

是否有可能或者我应该在没有jsvc包装器的情况下运行应用程序

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

还是有更好的解决方案?

4

1 回答 1

0

自己回答。只需在代码入口点的开头设置默认UncaughtExceptionHandler

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
于 2017-02-24T09:49:16.660 回答