Skip to content

Instantly share code, notes, and snippets.

@redmanmale
Last active January 24, 2017 14:15
Show Gist options
  • Save redmanmale/4c67764bff6ea4f82df761509a53466a to your computer and use it in GitHub Desktop.
Save redmanmale/4c67764bff6ea4f82df761509a53466a to your computer and use it in GitHub Desktop.
Basic log4net usage

Basic log4net usage

Following next few steps you will get very basic logging in your project. Logger will print to console as well as log file, placed in subfolder called Logs of the folder from which you run your app.

  1. Add log4net to your project using nuget.
  2. Create or modify your app.config according to example.
  3. Create log.config file, fill it according to example and set "Copy if newer" option in properties.
  4. Before call XmlConfigurator.Configure() all logging will not work.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net configSource="Log.config" />
<appSettings>
<add key="log4net.Internal.Debug" value="true" />
<add key="log4net.Internal.Quiet" value="true" />
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p [%d{HH:mm:ss}] [%t] %m %n" />
</layout>
</appender>
<appender name="LogFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs\" />
<encoding value="utf-8" />
<lockingmodel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Date" />
<datePattern value="yyyy_MM_dd.\tx\t" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p [%d{HH:mm:ss}] [%t] %m %n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="Console" />
<appender-ref ref="LogFile" />
</root>
</log4net>
using log4net;
using log4net.Config;
namespace Log4netBasicUsage
{
internal static class Program
{
private static readonly ILog _log = LogManager.GetLogger(typeof(Program));
internal static void Main()
{
XmlConfigurator.Configure();
_log.Info("Logging!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment