1

I use log4net for send mails to my app users. I must to have dynamic configuration for doing it. So I tried using GlobalContext.Properties for this, but it doesn't work!

Here is my code of original appender:

   <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
  <to value="myAddress@myComp.com" />
  <from value="myAddress@myComp.com" />
  <subject value="test logging message" />
  <smtpHost value="out.bezeqint.net" />
  <username value="myUserName" />
  <password value="myPassword />
  <authentication value="Basic" />
  <bufferSize value="512" />
  <lossy value="true" />
  <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="ERROR" />
  </evaluator>
  <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="WARN" />
  </evaluator>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %newline%newline - %message%newline" />
  </layout>
</appender>

at c#:

  ILog emailLog = log4net.LogManager.GetLogger("EmailLogger"); 
        log4net.Config.XmlConfigurator.Configure(emailLog.Logger.Repository);

        emailLog.Error("test aaa");

It works well. But, I tried to replace one of the properties to be dynamic- and it not works, the message have not sended.

at appender:

  <to value="%property{emailTo}" />

at C#:

  log4net.GlobalContext.Properties["emailTo"] = "myAddress@myComp.com";
        ILog emailLog = log4net.LogManager.GetLogger("EmailLogger"); 
        log4net.Config.XmlConfigurator.Configure(emailLog.Logger.Repository);

        emailLog.Error("test aaa");
user5260143
  • 1,048
  • 2
  • 12
  • 36
  • If you want to configure some or all fields of the `SmtpAppender` [dynamically, you can look at this answer.](https://stackoverflow.com/a/67433757/11671912) – Ruslan May 07 '21 at 11:15

1 Answers1

1

You have to tell log4net that the property uses a "pattern string":

<to type="log4net.Util.PatternString"  value="%property{emailTo}" />

From the documentation:

This string has embedded patterns that are resolved and expanded when the string is formatted.

stuartd
  • 70,509
  • 14
  • 132
  • 163
  • Is there a way to create and append an SMTP Appender to the log4net without and configuration in web.config file. – Cengiz Araz Jul 06 '16 at 19:19
  • @CengizAraz yes you can add one programatically – stuartd Jul 07 '16 at 08:27
  • Is there any reference that you can add here? Because all I saw through my searches people add the SmtpAppender into the config file and either override SendBuffer() or Append() method. I want to create something dynamic and to be able to define all properties of that SmtpAppender in my C# file. I will really appreciate it. – Cengiz Araz Jul 07 '16 at 15:36
  • Hey @CengizAraz, if you're still searching, check out [my answer on overriding the SmtpAppender programmatically](https://stackoverflow.com/a/67433757/11671912). – Ruslan May 07 '21 at 11:13