Home > .NET, Log4Net, Vs2017 > Steps for log4net in .NET Framework Console App

Steps for log4net in .NET Framework Console App

2018/12/27

In Visual Studio 2017 add from Nuget the Log4Net package.
.
In AssemblyInfo.cs add

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

In the class constructor where you want to use log4net add these lines, this is a skeleton for a Program.cs of a Console app

namespace MyProgram
{
    class Program
    {
        static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {
            log4net.Config.BasicConfigurator.Configure();
        }

Here we can note the typeof(Program), if we have a class named Test we must write typeof(Test), and the code log4net.Config.BasicConfigurator.Configure(); must be in the class constructor.
in app.config for a logging into a text file we must have something as

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net debug="true">
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\LogWeb\DocValidator-log.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="20" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
      </layout>
    </appender>
    <root>
      <priority value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <category name="my.category">
      <priority value="DEBUG" />
    </category>
  </log4net>

That is if we have a section configSections we must add the new line for log4.net, then add the entire log4net section.
Obvious, he folder must be writable for the IIS user.
If the logging is not working , add the key

<add key="log4net.Internal.Debug" value="true"/>

In the appSettings section of app.config : on the console there will be a very verbose output , that should address an eventual problem.

Categories: .NET, Log4Net, Vs2017