我创建了连接到Web服务的自定义Appender(带有AppenderSkeleton)...在此Appender中,我需要向Web服务发送一些自定义属性(例如Url,Browser,User,...)...
但是当我添加这样的属性时:

ThreadContext.Properties["addr"] = System.Web.HttpContext.Current.Request.UserHostAddress;

在我的appender中,像这样:
public class UrlLogAppender : AppenderSkeleton
    {

        public string APIkey { get; set; }
        public string CustomerName { get; set; }

        protected override void Append(LoggingEvent loggingEvent)
        {
            try
            {
                Base.LogToDataBase.WebService1 LogtoWebserver = new Base.LogToDataBase.WebService1();



                string Result = LogtoWebserver.Log(CustomerName, APIkey, loggingEvent.TimeStamp.ToString(), loggingEvent.ThreadName.ToString(), loggingEvent.Level.ToString(), loggingEvent.LoggerName, loggingEvent.RenderedMessage, loggingEvent.ExceptionObject.InnerException.Message.ToString(), loggingEvent.Properties["addr"].ToString(), loggingEvent.Properties["browser"].ToString(), loggingEvent.Properties["url"].ToString());
                if (Result != "UnSucced!!")
                {
                    //Say Excellent.... !
                }
                else
                {
                    //Say Opps....!!

                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("An error occured while invoking the Logging REST API", ex);
            }
        }

        public UrlLogAppender()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }
}`

我无法捕捉到我之前添加和填充的属性(**loggingEvent.Properties["browser"].ToString()**?!?!?!!!!?)

我的Web.Config像这样:
  <appender name="UrlAppender" type="log4net.Extensions.UrlLogAppender">
      <threshold value="ALL"/>
      <CallingApp value="Base" />
      <datePattern value="_yyyy-MM-dd.lo'g'"/>
      <APIkey value="321" />
      <CustomerName value="Kanon" />

      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date User:%identity IP:%X{addr} Browser: %X{browser} Url: %X{url} [%thread] %-5level %c:%m%n"/>
      </layout>
    </appender>

请帮我 !

最佳答案

您可以通过两种方式访问​​在XML文件中配置的属性。如果您有这样的配置:

<appender name="Test" type="MyAppender, MyAssembly">
    <intProperty>1234</intProperty>
    <stringProperty>hello</stringProperty>

    <layout> ... </layout>
</appender>

您的Appender类如下所示:
public class MyAppender : AppenderSkeleton
{
    public int IntProperty { get; set; }

    public override void Append(LoggingEvent loggingEvent)
    {
        // implement your functionality
    }

    public void AddStringProperty(string value)
    {
        // do whatever has to be done
    }
}

您可以从配置文件中指定与XML元素同名的公共(public)属性,也可以提供一个公共(public)方法,该方法只接受一个参数(XML元素的值),并命名为Add<name of XML element>。 log4net将搜索您的appender类中的一个(大小写不变),并在初始化appender时调用它们。

关于c# - 如何在AppenderSkeleton log4net中添加自定义属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17120943/

10-11 02:02