问题
I am creating a custom wrapper for log4net. I am trying to fill my LoggingEventData object and there are some custom properties I want to pass to the Appender's append
Method.
However, this these properties are intermediate properties, so I don't want them to be in the appenders configuration.
LoggingEventData.Properties is a read only dictionary. Is there a way get a value in there for me to pass a custom property (via LoggingEventData) to the appender WITHOUT having to update the appender or a config file?
回答1:
It's not really clear what you want to do, and I suspect that whatever it it is, the LoggingEventData path may not be the best, unless you can use the LoggingEvent constructor that takes a LoggingEventData instance in your wrapper.
What may be of use is that you can easily store data in the log4net context and retrieve it when logging.
You set it in your logging code thus:
// Other contexts are available
// http://logging.apache.org/log4net/release/manual/contexts.html
log4net.GlobalContext.Properties["value1"] = "Value 1";
And retrieve it in the appender pattern, e.g.:
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%value1 (%property{value1})" />
</layout>
</appender>
As it says in this useful blog post on the subject:
Context property values don't have to be strings. You can set the value of a context property to any object reference; the value of the object's ToString method will be used to obtain the context property value when a logging event occurs
来源:https://stackoverflow.com/questions/28775568/add-a-custom-property-to-a-loggingeventdata-programmatically