简体   繁体   English

在C#中使用Log4Net动态添加自定义字段

[英]Add Custom Fields using Log4Net dynamically in c#

I am trying to add some custom fields in my log using c#. 我正在尝试使用c#在日志中添加一些自定义字段。 I am able to do that when I know about all the fields. 当我了解所有领域时,我就能做到。

Now, in one scenario I don't know the number of fields. 现在,在一种情况下,我不知道字段的数量。 Eg I have to add the parameters of the object and the numbers of object will keep on changing during run-time and I need to add the fields depending upon the number of objects. 例如,我必须添加对象的参数,并且对象的数量将在运行时不断变化,并且我需要根据对象的数量添加字段。

Is there any tweak can be done in log4net to accomplish this so whenever there is a new Object the new field get created. 在log4net中是否可以进行任何调整以完成此操作,因此,每当有新对象时,都会创建新字段。

I am not sure mainly how to handle this in the config file for log4net. 我不确定主要如何在log4net的配置文件中处理此问题。

You can add the properties of your object in a custom property for log4net and log the content of the property in your formatting: 您可以在log4net的自定义属性中添加对象的属性 ,并以格式记录该属性的内容:

For example in your code: 例如在您的代码中:

log4net.ThreadContext.Properties[ "myObjectProperties" ] = obj.prop1 + " " obj.prop2; // + ...;

and in the configuration: 并在配置中:

 <conversionPattern value="%logger (%property{myObjectProperties}) [%level]- %message%newline" />

You cannot have a pattern that is configurable on the fly; 您不能动态配置一个模式。 you could have multiple patterns that would match different objects but this won't be very easy to manage. 您可能有多个可以匹配不同对象的模式,但这很难管理。

EDIT: well, you could have a runtime configurable pattern but not natively :) However you could perhaps have a pattern that is able to be loaded from the aforementioned properties 编辑:好吧,您可能有一个运行时可配置的模式,但不是本机的:)但是,您也许有一个能够从上述属性中加载的模式

2nd EDIT: If there are as much as 4000 properties you need, why not consider either pushing all those properties as part of the message itself ( log.Info(myObject.ToString()) ) or create a custom appender that would be able to handle a specific interface to process: 第2编辑:如果需要多达4000个属性,为什么不考虑将所有这些属性作为消息本身的一部分来推送( log.Info(myObject.ToString()) )或创建一个自定义附加程序处理特定的接口以进行处理:

public interface IHaveManyFieldsToLog
{
    public string[] GetAllPropertyValues()
}

public class ManyFieldsToLogAppender: SkeletonAppender
{
    // pseudocode, I don't have the IDE at the moment
    public override AppendLog(LogEvent event)
    {
         if (event.Parameter[0] as IHaveManyFieldsToLog != null)
         {
              var values = (event.Parameter[0] as IHaveManyFieldsToLog).GetAllPropertyValues();
              // concat all values and push it to the log
         }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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