Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log Trace messages with log4net?

Tags:

c#

.net

log4net

I'm using log4net to log write log message to a rolling log file.

Now I would also redirect all trace messages from System.Diagnostics.Trace to that log file. How can I configure that? I tried to find anything about that in the log4net documentation, but without success. Is it possible at all?

The reason I want to do that is because I am interested in the Trace messages of a 3rd party library.

<log4net>     <appender name="R1" type="log4net.Appender.RollingFileAppender">       <file value="C:\Logs\MyService.log" />       <appendToFile value="true" />       <rollingStyle value="Date" />       <maxSizeRollBackups value="10" />       <datePattern value="yyyyMMdd" />       <layout type="log4net.Layout.PatternLayout">         <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />       </layout>     </appender> </log4net> 
like image 772
Dirk Vollmar Avatar asked Feb 05 '09 10:02

Dirk Vollmar


People also ask

Where do log4net logs go?

In your case, the log file will be in bin\Debug\netcoreapp3.

Is log4net structured logging?

log4net doesn't support the concept of structured logging. Like shown in the conversionPattern element in the XML configuration, you have some variables to play with when writing to the storage. But including properties like FirstName in the Serilog example isn't available.

How do I use log4net net 6?

Just create a log4net. config file with a log file as an appender, then add two using statements and a single line of code to the new . NET 6 hosting model: //Program.


1 Answers

According to Rune's suggestion I implemented a basic TraceListener which output to log4net:

public class Log4netTraceListener : System.Diagnostics.TraceListener {     private readonly log4net.ILog _log;      public Log4netTraceListener()     {         _log = log4net.LogManager.GetLogger("System.Diagnostics.Redirection");     }      public Log4netTraceListener(log4net.ILog log)     {         _log = log;     }      public override void Write(string message)     {         if (_log != null)         {             _log.Debug(message);         }     }      public override void WriteLine(string message)     {         if (_log != null)         {             _log.Debug(message);         }     } } 
like image 108
Dirk Vollmar Avatar answered Sep 23 '22 19:09

Dirk Vollmar