Using log4j to send email reports via the SMTPAppender

后端 未结 3 1169
粉色の甜心
粉色の甜心 2020-12-02 23:58

I\'m trying to use log4j to send emailable reports that contain the logging statements from a background process. I want one email sent for each process run, not one email

3条回答
  •  星月不相逢
    2020-12-03 00:47

    You shouldn't use any of log4j's methods, you should configure it properly instead.

    First of all, define in your log4j.properties file your appender properly:

    #CONFIGURE SMTP
    log4j.appender.email=org.apache.log4j.net.SMTPAppender
    log4j.appender.email.SMTPHost=mail.mydomain.com
    log4j.appender.email.SMTPUsername=myuser@mydomain.com
    log4j.appender.email.SMTPPassword=mypw
    log4j.appender.email.From=myuser@mydomain.com
    log4j.appender.email.To=myuser@mydomain.com
    log4j.appender.email.Subject=Log of messages
    log4j.appender.email.BufferSize=1
    log4j.appender.email.EvaluatorClass=TriggerLogEvent
    log4j.appender.email.layout=org.apache.log4j.PatternLayout
    log4j.appender.email.layout.ConversionPattern=%m
    

    Note: code taken from this post. More information can be obtained in SMTPAppender API.

    Next, make a special class that will be used just for sending email. Example:

    package com.foo.mailer;
    import org.apache.log4j.Logger;
    
    public class Mailer {
       private static final Logger logger = Logger.getLogger(Mailer.class);
    
       public void logMail(String mailString) {
          logger.info(mailString);
       }
    }
    

    Next, put in log4j.properties configuration for this class:

    # INFO level will be logged
    log4j.logger.com.foo.mailer = INFO, email
    # turn off additivity
    log4j.additivity.com.foo.mailer = false
    

    Now, whenever you want to send an email using log4j, put this in your code:

    new Mailer().logMail("This mail should be sent");
    

    Disclaimer: I haven't tested any of this code.

提交回复
热议问题