How to Use Logger in WPF Application

Steps to Follow
Create a WPF application in Visual Studio.

Making appropriate changes in "log4net.config" File

Go to NuGet package manager.

Select Manage NuGet Packages for Solution.

Select log4net by Apache Software.

Add a config file to project name it as “log4net.config”.

Select Application Configuration File from menu.

Rename file to “log4net.config”.

Select log4net.config from solution explorer, see for options in properties :

Build Action → Change to “ Content”.

Copy to output directory → Change to “copy always”.

Making appropriate changes in "log4net.config" File

<?xml version="1.0" encoding="utf-8" ?>
			<level value="ALL" />
			<appender-ref ref="console" />
			<appender-ref ref="file" />
		<appender name="console" type="log4net.Appender.ConsoleAppender">
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date %level %logger - %message%newline" />
		<appender name="file" type="log4net.Appender.RollingFileAppender">
			<file value="C:\CsharpCode\WPFapp.log" />
			<appendToFile value="true" />
			<rollingStyle value="Size" />
			<maxSizeRollBackups value="5" />
			<maximumFileSize value="2MB" />
			<staticLogFileName value="true" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
Open AssemblyInfo.cs from solution explorer and add at the end.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Configure App.xaml.cs file

Add 'using log4net;' reference.

Add these codes inside “public partial class App : Application” :

private static readonly ILog log = LogManager.GetLogger(typeof(App));
        protected override void OnStartup(StartupEventArgs e)
            log.Info("        =============  Started Logging  =============        ");
Open MainWindow.cs

Add reference :
using log4net;
Add these codes inside “public partial class MainWindow”
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Inside public MainWindow() :

Options available for logs :
  *  log.info
  *  log.error
  *  log.fatal
  *  log.debug



0 Comment's

Comment Form