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,
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);
}
}
}
}
Best ASP.NET Core 7.0.2 Hosting Recommendation
One of the most important things when choosing a good ASP.NET Core 7.0.2 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core 7.0.2 , their servers are optimized for PHP web applications such as the latest ASP.NET Core 7.0.2 version. The performance and the uptime of the ASP.NET Core 7.0.2 hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core 7.0.2 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core 7.0.2. And the engineers do regular maintenance and monitoring works to assure its ASP.NET Core 7.0.2 hosting are security and always up.