AllSolutions
AllSolutions

Reputation: 1266

log4net log messages only to a few appenders

I am using log4net api for logging in my WinForms application. I have multiple appenders: RollingFileAppender and TextBoxAppender (custom appender).

I want to log some Error messages only in the log file (RollingFileAppender) and not to the text box (TextBoxAppender), and some other messages to both. How can I achieve it? Note that the messages are of same level i.e. all ERROR messages.

Thanks.

EDIT 1:

Specifically, I want to display simple one line ERROR messages in the UI as well as log file, but StackTraces only in the log file.

Upvotes: 0

Views: 1399

Answers (2)

Jeroen Mostert
Jeroen Mostert

Reputation: 28769

As I understand it, you actually want messages to go to both appenders, but have only one of them log stack traces. First, log messages including the exception as an exception, don't use Exception.ToString():

logger.Error($"Something went wrong frobbing the widget: {ex.Message}", ex);

Then your logger can use multiple appenders, some of which omit the stack trace by telling log4net we'll be taking care of exceptions (by actually doing nothing with them):

<appender name="TextBoxAppender" type="MyAppenders.TextBoxAppender">
    <layout type="log4net.Layout.PatternLayout">
        <ignoresException value="false" />
        <conversionPattern value="%m%n" /> 
    </layout>
</appender>

And others with full details:

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
    ...
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{ISO8601} [%t] %-5p %c - %m%n" />
    </layout>
</appender>

Upvotes: 2

swe
swe

Reputation: 1455

The solution to output different messages to different appenders should be the ForwardingAppender (the documentation on logging.apache seems to be down at the present, but anyway here is the link: https://logging.apache.org/log4net/release/sdk/log4net.Appender.ForwardingAppender.html)

Here you can filter based on loglevel (most examples) but also based on log messages (have a look here: http://www.codeproject.com/Articles/140911/log-net-Tutorial, Paragraph "StringMatchFilter")

At least, this helps you to bring just this one message to one specific Appender. To make sure how to omit the stacktrace see Jeroen Mosterts answer

Upvotes: 1

Related Questions