DEV Community

hackhyun
hackhyun

Posted on

[C#] log4net usage

This is how to use log4net to process logging in .Net environment.

  1. Search for log4net in Visual Studio's NuGet package management and install it.

  2. When the installation is complete, log4net is added to the references.

  3. Create a new configuration file and add it.

<?xml version="1.0" encoding="utf-8"?>

<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFileAppender" />
  </root>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <!--<file type="log4net.Util.PatternString" value="log-%property{processid}-%date{yyyy-MM-dd}.txt" />-->
    <file value="Log\common.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
    </layout>
  </appender>
</log4net>
Enter fullscreen mode Exit fullscreen mode

For details on how to create the configuration file, see here.

  1. The configuration file may exist as a separate file when distributing the program, but here, in order to include it in the assembly, designate the build operation as 'embedded resource' in the property window.

  2. Now we actually do log processing where we want to leave logs.

namespace log4net_test
{
    internal class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {
            var assembly = typeof(Program).Assembly;
            using (var stream = assembly.GetManifestResourceStream("log4net_test.config.log4net.config"))
            {
                log4net.Config.XmlConfigurator.Configure(stream);
            }

            log.Info("Application started");
            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
            log.Info("Application ended");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, the configuration file as an embedded resource is passed as an argument value of the GetManifestResourceStream() method. In the case of the example, since the 'config' folder was created and the configuration file was placed under it, the folder name was '.' You need to put it between the namespace and the file name as above.

If you run the program after building, the log file specified in the configuration file, Log\common_log, will be created and the log will remain.

Top comments (0)