问题描述
我正在使用类似这样的命令在Linux服务器上启动我的应用程序
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
我正在使用log4j
登录我的应用,并且它具有log4j.properties
中描述的自己的配置,该配置位于myapp.jar
内部.
I'm using log4j
for logging in my app and it has own configuration described in log4j.properties
which is located inside myapp.jar
.
我希望能够捕获应用程序中发生的任何异常并通过电子邮件将其发送给我.为此,我已经在log4j.properties
中配置了org.apache.log4j.net.SMTPAppender
.
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.
但是,当前RuntimeException
(例如NullPointerException
)只是打印到stderr
,而jsvc
会重定向到error.log
,而无需应用log4j
格式设置模式.
But currently RuntimeException
, like NullPointerException
are just printed to stderr
which jsvc
redirects to error.log
without applying log4j
formatting pattern.
是否有可能或应该在没有jsvc
包装程序的情况下运行该应用程序
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?
推荐答案
正在回答自己.只需将默认 UncaughtExceptionHandler 设置为代码入口点的开头
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
[email protected]
log4j.appender.email.SMTPPassword=yourpassword
[email protected]
[email protected]
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
这篇关于在Java应用程序中捕获RuntimeExceptions并通过电子邮件发送它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!