How to use log4net for logging in C#
By FoxLearn 12/24/2024 9:49:44 AM 14.27K
What is log4net?
Log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in shipped code without incurring a high performance cost.
How To Start Logging With Log4net
Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "Logging" and then click OK
You need to install the log4net package in your project by right-clicking on your project select Manage NuGet Packages -> Search for log4net then install it.
You can do this via NuGet Package Manager Console by running the following command
Install-Package log4net
Log4net for .NET Logging
At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity. Log4net is designed with two distinct goals in mind: speed and flexibility.
Open your form designer, then drag and drop the Button controls from the Visual Studio toolbox onto your form as shown below.
In this example, we will save log4net into database, so you need to create a Log table as shown below.
CREATE TABLE [dbo].[Log] ( [Id] [int] IDENTITY (1, 1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar] (255) NOT NULL, [Level] [varchar] (50) NOT NULL, [Logger] [varchar] (255) NOT NULL, [Message] [varchar] (4000) NOT NULL, [Exception] [varchar] (2000) NULL )
Add log4net.config File
Add a new file named log4net.config
or log4net.xml
to your project in Visual Studio, and set the "Copy to Output Directory" property to "Copy Always" to ensure the file is copied to the output directory during build.
Below is a sample XML configuration for logging to a SQL Server database:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <root> <level value="ALL"></level> <appender-ref ref="AdoNetAppender"></appender-ref> </root> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="data source=.;initial catalog=dblog;integrated security=false;persist security info=True;User ID=sa;Password=123@qaz" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> </configuration>
You can add the log4net config into your app.config file. Don't forget to modify the connectionString
value with your SQL Server connection string, and adjust the commandText
value according to your database schema.
Log4net log to database example
In your C# code, configure log4net to use this configuration file.
Add this line early in your application initialization:
log4net.Config.XmlConfigurator.Configure(new FileInfo("path/to/log4net.config"));
Make sure to replace "path/to/log4net.config"
with the actual path to your log4net configuration file.
If you don't use the log4net.config
you can config like this
log4net.Config.XmlConfigurator.Configure();
Now you can start logging messages from anywhere in your code. Import the log4net namespace (using log4net;
) and use the ILog
interface to get a logger instance.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Logging { public partial class Form1 : Form { public Form1() { InitializeComponent(); } log4net.ILog log; private void Form1_Load(object sender, EventArgs e) { //Load config log4net.Config.XmlConfigurator.Configure(); log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); } private void button1_Click(object sender, EventArgs e) { //Logging information log.Info("Your data has been successfully saved."); } private void button2_Click(object sender, EventArgs e) { int x = 0; try { int y = 1 / x; } catch(Exception ex) { //Logging error log.Error(ex.Message, ex); } } } }
Use appropriate log4net logging levels Debug, Info, Warning, Error, and Fatal within your code. Avoid logging everything as Debug and consider how you'll view the logs later.
In your log4net configuration, you can define which logging levels to record, allowing you to log specific data to certain appenders or reduce logging in production. Proper use of levels and filters helps control the amount of data logged without altering the code.
log4net Levels:
- All: Log everything
- Debug: Detailed information for debugging
- Info: General information about application flow
- Warn: Warnings about potential issues
- Error: Errors that affect functionality
- Fatal: Critical errors causing application failure
- Off: Disable logging
If you encounter issues with a specific appender or face difficulties using it, enabling internal log4net logging can help diagnose and resolve these problems. To enable it, add the following line before using the logger:
log4net.Util.LogLog.InternalDebugging = true;
You can also customize your configuration by adjusting pattern layouts to control which fields are output and in what format.
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="stackify.log" /> <param name="AppendToFile" value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd hh:mm:ss.ffff} [%thread] %m%n" /> </layout> </appender>
The layout configuration includes fields for logging the log level (%p), current date/time (%d), thread number (%thread), message (%m), and a new line (%n). The -5 in %-5p sets the log level field width to 5 characters.
Additional fields for logging (though potentially impacting performance in production) include:
- %method: Logs the method name where the message was written.
- %stacktrace{level}: Outputs a stack trace showing where the log message was written.
- %type: Logs the caller's class name.
- %line: Logs the line number from which the log statement was made.
When you log messages using log4net, it will write them to the configured SQL Server database according to the configuration you provided. You now have log4net integrated into your C# Windows Forms application, and you can start logging messages for debugging and monitoring purposes.
VIDEO TUTORIAL