Set log name in appender of log4net

若如初见. 提交于 2019-12-22 09:43:05

问题


I have class MyLogger, where I use log4net. How can I modify my appender to save log in specific logname (I want to set it by parameter logName).

public void AddEntry(string source, string logName, string contextInfo, string message, EventLogEntryType eventType)
        {

             log4net.ILog Log = log4net.LogManager.GetLogger(source);

             Log.Error(String.Format("Context Info: {0}{1}{2}{3}", contextInfo, Environment.NewLine, Environment.NewLine, message));

        }

<log4net>
  <root>
    <priority value="ALL" />
     <appender-ref ref="EventLogAppender" />
  </root>

This is myAppender. Now it writes in common logtype Application.

  <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%logger (%property{myContext}) [%level]- %message%newline" />
    </layout>
  </appender>
</log4net>

回答1:


I think what you are looking for is this:

<param name="LogName" value="MyLog" />

Some more information can be found here. If you do something like this you may want to have a look at this issue as well. Basically this is about registering your application so that the eventlog knows about it.

Edit (configuration by code):

Did not test it but that ought to do the trick:

foreach (AppenderSkeleton appender in this.Logger.Repository.GetAppenders())
{
    var eventlogAppender = appender as EventLogAppender;
    if (eventlogAppender != null)
    {
        eventlogAppender.LogName = "MyLog";
        eventlogAppender.ActivateOptions();
        break;
    }
 }

You could add some tests to verify that there is only one EventLogAppender, but probably you do not need to bother to do so.




回答2:


this works:

<param name="LogName" type="log4net.Util.PatternString" value="%property{LogName}" />


来源:https://stackoverflow.com/questions/3530646/set-log-name-in-appender-of-log4net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!