Log4Net SmtpAppender put threshold in subject line

2019-07-15 03:41发布

问题:

Greetings Stackoverflow users,

I have a c# windows service using log4net that will send out emails when there are errors. We now have the problem of getting emails for "expected" and "normal" errors, that is something went wrong but the service is still working and nothing has to be done. So the one easy solution is to identify our "expected" errors and log them as "WARN" instead of errors.

It would be great if log4net could send emails for both our "WARN" level and "ERROR" level events, and in the subject line identify what the level is. So the "WARN" levels can automatically be routed to a folder to look at sometime in the future and the "ERRORS" can be directly identified and looked at.

Question: Is it possible to get the trigger value, that is "WARN" or "ERROR" into the subject line??

I tried to make two SmtpAppender blocks in the configuration file, but that did not work.

Thank-you for your help.

回答1:

You can create two separate appenders and setup a LevelRangeFilter for each one, like this:

<appender name="WarnSmtpAppender" type="log4net.Appender.SmtpAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <levelMax value="WARN" />
    </filter>
    <to value="to@domain.com" />
    <from value="from@domain.com" />
    <subject value="Warning logging message" />
    <smtpHost value="SMTPServer.domain.com" />
    <bufferSize value="512" />
    <lossy value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
    </layout>
</appender>

<appender name="ErrSmtpAppender" type="log4net.Appender.SmtpAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR" />
        <levelMax value="ERROR" />
    </filter>
    <to value="to@domain.com" />
    <from value="from@domain.com" />
    <subject value="Error logging message" />
    <smtpHost value="SMTPServer.domain.com" />
    <bufferSize value="512" />
    <lossy value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
    </layout>
</appender>

Then, you setup your logger with both appenders:

<root>
    <!-- Log4Net available levels:
      ALL DEBUG INFO WARN ERROR FATAL OFF-->
    <level value="WARN" />
    <appender-ref ref="WarnSmtpAppender" />
    <appender-ref ref="ErrSmtpAppender" />
</root>

Please note that the LOGGER level must be set to WARN or lower. If set to ERROR, the logger will not emit Warnings, so the Warn appender will not get them.

This should do the trick.