Log4Net is probably familiar to all of you, and is one of the more mainstream and well-known logging components.
- Website: logging.apache.org
- Open source: github.com/apache/logg…
Best practices
Add component packages to your project
Install-Package log4net
Copy the code
Add the log4net.config file
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net debug="false">
<appender name="info" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="log4net/info/" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="1"/>
<param name="MaximumFileSize" value="5MB"/>
<param name="RollingStyle" value="Composite" />
<param name="DatePattern" value="yyyyMMdd\\HH".log"" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%n
{
"system": "Meowv.Blog"."datetime": "%d"."description": "%m"."level": "%p"."info": "%exception"
}" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
<appender name="error" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="log4net/error/" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="1"/>
<param name="MaximumFileSize" value="5MB"/>
<param name="RollingStyle" value="Composite" />
<param name="DatePattern" value="yyyyMMdd\\HH".log"" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%n
{
"system": "Meowv.Blog"."datetime": "%d"."description": "%m"."level": "%p"."info": "%exception"
}" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="ERROR" />
</filter>
</appender>
<root>
<level value="ALL"></level>
<appender-ref ref="info"/>
<appender-ref ref="error"/>
</root>
</log4net>
</configuration>
Copy the code
Console project
using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Reflection;
namespace ConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
var log4netRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config"));
ILog log = LogManager.GetLogger(log4netRepository.Name, "NETCorelog4net");
log.Info("NETCorelog4net log");
log.Info("test log");
log.Error("error");
log.Info("linezero"); Console.ReadKey(); }}}Copy the code
AspNetCore project
Create a new static class and write an extension method UseLog4Net() for log4NET initialization.
public static class Log4NetExtensions
{
public static IHostBuilder UseLog4Net(this IHostBuilder hostBuilder)
{
var log4netRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config"));
returnhostBuilder; }}Copy the code
The extension method returns the IHostBuilder object, which can be called chained, beautifying the code, and then using the extension method UseLog4Net() in program.cs.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace WebAppDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)=> Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).UseLog4Net(); }}Copy the code
The configuration is complete, then write to the log anywhere.
using log4net;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WebAppDemo.Controllers{[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing"."Bracing"."Chilly"."Cool"."Mild"."Warm"."Balmy"."Hot"."Sweltering"."Scorching"
};
private readonly ILog _log;
public WeatherForecastController()
{
_log = LogManager.GetLogger(typeof(WeatherForecastController));
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_log.Info("Hello, this is a Weather api!");
_log.Warn("Wran !!!");
_log.Error("Controller Error");
var rng = new Random();
return Enumerable.Range(1.5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(- 20.55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); }}}Copy the code