Daily log using log4net in worker service

Introduction

This article will explain how to do daily based logging using Log4Net in Worker Service. Create one Worker service in .Net core latest version and install the package of Log4net from Manage Nuget packages,

Daily log using log4net in worker service

Create a Log class and add the below code for error, debug and info functions to write a log message in log files.


    public interface Log
    {
        void Debug(string msg);
        void Info(string msg);
        void Error(string msg, Exception? ex = null);
    }
    public class Logger : Log
    {

        private readonly ILog _logger;
        public Logger()
        {
            this._logger = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);
        }
        public void Debug(string msg)
        {
            this._logger?.Debug(msg);
        }
        public void Info(string msg)
        {
            this._logger?.Info(msg);
        }
        public void Error(string msg, Exception? ex = null)
        {
            this._logger?.Error(msg, ex?.InnerException);
        }
    }

Below is the code to create a file on daily date vice and append a log content

<datePattern value="yyyyMMdd'.log'"/>
<appendToFile value="true" />
<staticLogFileName value="false"/>

Add a config file and name it as log4Net.config. Also, add the below configuration code,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<log4net>
		<root>
			<level value="ALL" />
			<appender-ref ref="DebugLog" />
			<appender-ref ref="ErrorLog" />
		</root>
		 
		<appender name="DebugLog" type="log4net.Appender.RollingFileAppender">
			 <filter type="log4net.Filter.LevelMatchFilter">
              <levelToMatch value="INFO"/>
          </filter>
			<file value="C:\Log\Debug\Debug_" />
			<datePattern value="yyyyMMdd'.log'"/>
			<appendToFile value="true" />
			<staticLogFileName value="false"/>
			<maximumFileSize value="100MB" />
			<maxSizeRollBackups value="2" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
			</layout>
		</appender>
		<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
			 <filter type="log4net.Filter.LevelMatchFilter">
              <levelToMatch value="ERROR"/>
          </filter>
			<file value="C:\Log\Error\Error_" />
			<datePattern value="yyyyMMdd'.log'"/>
			<appendToFile value="true" />
			<staticLogFileName value="false"/>
			<maximumFileSize value="100MB" />
			<maxSizeRollBackups value="2" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
			</layout>
		</appender>
			 
	</log4net>
</configuration>

Worker service code for logging.


using log4net.Config;
namespace WorkerService
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetEntryAssembly()),
                  new FileInfo("log4Net.config"));
            Logger log = new Logger();
            log.Error("Error Message");
            log.Debug("Debug Message");
            while (!stoppingToken.IsCancellationRequested)
            {               
               _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);                                
                await Task.Delay(1000, stoppingToken);                
            }
        }       
    }
}


Similar Articles