I'm trying to setup Log4Net (this is my first time using Log4Net) to log to a text file in an assembly. I'm not getting any errors, but it's also not working. I can breakpoint the lines where I am logging my output and see that they are reached, but like I say nothing happens.
Where am I going wrong?
I have added the following to my packages.config
file, inside the <packages>
attribute:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="c:\CTI\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
I have added the following line to AssemblyInfo.cs
:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
I added the Log4Net assembly using NuGet and I am logging like this:
private log4net.ILog _Log;
_Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
_Log.Debug("FooBar");
Like I say, no errors but nothing happens either.
What am I missing?
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.
One thing that is wrong is that you are adding the log4net configuration section to the nuget config file (packages.config
).
You can have the configuration in the app/web config or in a separate file to which you point from the appSettings, e.g.
configuration is in a file called config.log4net
(the copy to output directory
attribute of the file is set to copy always
) and you add the following entry in app/web.config:
<add key="log4net.config" value="config.log4net"/>
If you don't want to depend on a web/app configuration, you can set the ConfigFileExtension property of the XmlConfiguratorAttribute
attribute in AssemblyInfo.cs
:
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "log4net", Watch = true)]
Then name the log4net configuration file the same as your exe/assembly plus the configured extension, e.g. MyApplication.exe.log4net
or MyLibrary.dll.log4net
Another thing that is wrong is your appender filter. The range that you have set excludes DEBUG level, which you expect to log. Here are all logging levels:
ALL
DEBUG
INFO
WARN
ERROR
FATAL
OFF
As you can see, DEBUG
is not between INFO
and FATAL
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With