Conditional logging with log4net

自古美人都是妖i 提交于 2020-01-05 07:31:10

问题


I have a program that uses log4Net using both text and smtp appenders.

When the program runs several logging are captured by the smtp appenders and are buffered waiting for the program end before sending mail.

When the program is nearly completed I might discover that I do not need to send emails, and actually I log something like "Nothing to do".

I know that it is possible to manipulate by code the appenders configuration so I could suppress the mail setting the Threshold to off.

I would like to know if it is possible to get the same result using just log4net configuration: the smtp appender should not send an email if a specific string is logged at any time. If instead that string is not logged it should behave normally and send all the lines that match the defined filters.


回答1:


TL;DR;

  • create a custom ITriggeringEventEvaluator
  • configure your smtp appender with this evaluator: decide what must happen when the buffer is full (discard messages, send them)
  • use the auto-flush of your appender to send the log events forward

There are two properties in a BufferingAppenderSkeleton in log4net that may interest you here. When you configure such an appender to be Lossy, Evaluator and LossyEvaluator are used to determine if messages should be sent to the next appenders.

The Evaluator property lets you define a class inheriting from ITriggeringEventEvaluator; when a message is logged and the buffer is full, the evaluator is called and if it returns true on the IsTriggeringEvent method the event buffer is processed. The LossyEvaluator works in the same way, except it is called to decide whether the oldest event that will disappear from the buffer because it is full must be logged or not.

Since your SmtpAppender is a BufferingAppenderSkeleton, you can use the Evaluator property in order to define what triggers or not the email being sent (ie a logging event where you say "no log", or whatever)

However if you expect your appender to decide on its own whether or not to send the event logs when it is closed (ie should it auto-flush or not) it is the LossyEvaluator that is used.

Now for the bad news: there is only one instance of a ITriggeringEventEvaluator implementation in log4net, which evaluates log events based on their level. So you will have to code your own trigger in order to recognize special messages sent to the appender by your application.



来源:https://stackoverflow.com/questions/25894103/conditional-logging-with-log4net

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