简体   繁体   中英

How to pass email address as parameter from C# code to log4net smtp appender

I am using log4net smtp appender to send email alerts in case of an error in the application. Is there a way I can assign the email address at run time rather than putting in the config file. The config file is :

<appender name="LogSmtpAppender" type="log4net.Appender.SmtpAppender">
      <authentication value="Basic" />
      <to value="" />

I am initializing the logger from my application as:

 public static readonly log4net.ILog applicationLog = log4net.LogManager.GetLogger("MyApplication");

You can get the appender and then change the configuration by setting the property and then activate the new options like:

        // Get the Hierarchy object that organizes the loggers
        Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy;
        var smtpappender =
                (SmtpAppender)hier.GetAppenders().Where(
                    appender => appender.Name.Equals("LogSmtpAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (smtpappender != null)
            {
                // Change your setting here
                smtpappender.To = "new@value.com"
                // Activate the options
                smtpappender.ActivateOptions(); 
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM