Log4j programmatically setting SMTP settings is no

2019-09-07 05:43发布

I'm using Log4j to send email logs on errors, and want to set the SMTP settings in log4j in java, and not in a properties file. Setting the password works, and i can successfully send an email with it

private static final Logger logger = Logger.getLogger("emailer");

(...)

Enumeration<?> enm = logger.getAllAppenders();
while (enm.hasMoreElements()) {
    Object element = enm.nextElement();
    if (element instanceof SMTPAppender) {
        ((SMTPAppender) element).setSMTPPassword(password);
    }
}

However, using the other setters in SMTPAppender does nothing ( setting host, username, etc. ), and log4j will keep using the properties file's settings.

(...)

log4j.logger.emailer=stdout, email
log4j.additivity.emailer=false

log4j.appender.email=org.apache.log4j.net.SMTPAppender
log4j.appender.email.SMTPHost=smtp.gmail.com
log4j.appender.email.SMTPPort=465
log4j.appender.email.SMTPUsername=username@gmail.com
log4j.appender.email.SMTPPassword=-
log4j.appender.email.From=username@gmail.com
log4j.appender.email.to=username@gmail.com
log4j.appender.email.Subject=Error Alert
log4j.appender.email.layout=org.apache.log4j.PatternLayout
log4j.appender.email.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
log4j.appender.email.BufferSize=10
log4j.appender.email.Threshold=ERROR

标签: java smtp log4j
1条回答
冷血范
2楼-- · 2019-09-07 06:24

It looks like you need to call activateOptions() after you change the name or password.

查看更多
登录 后发表回答