我无法使用 log4j2 发送错误邮件。此外,它没有显示任何类型的异常或其他东西。这是我的 log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="LogToConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingRandomAccessFile name="LogToRollingRandomAccessFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingRandomAccessFile>
<SMTP name="LogToMail" subject="Capacity Platform: Error mail notification"
from="sendermail@domain.com"
to="receivermail@domain.com"
smtpHost="<mySMTP>"
smtpPort="<smtpPort>"
smtpUsername="<username>"
smtpPassword="<password>"
bufferSize="100">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</SMTP>
</Appenders>
<Loggers>
<Logger name="com" level="info">
<AppenderRef ref="LogToConsole"/>
<AppenderRef ref="LogToRollingRandomAccessFile"/>
</Logger>
<Root level="error" additivity="false">
<AppenderRef ref="LogToMail"/>
</Root>
</Loggers>
</Configuration>
我能够创建日志文件 (app.log) 并能够使用此 log4j2.xml 在控制台上打印错误,但是我无法发送错误邮件。
这是java代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ErrorClassSample {
static final Logger logger= LoggerFactory.getLogger(ErrorClassSample.class);
public void errorMethod() {
try {
System.out.println(getData());
} catch (IllegalArgumentException e) {
logger.error("{}", e);
}
}
private int getData() throws IllegalArgumentException {
throw new IllegalArgumentException("Sorry IllegalArgumentException!");
}
}
我在 Spring 4.0.2 中使用它。