Original: Interpreting ASP 5 & MVC6 Series (9): Log frame
Framework Introduction
In the previous. NET, Microsoft has not provided a decent log framework, some of the frameworks currently available such as Log4net, NLog, commonlogging are more or less laborious to use, and Java's slf4j can not be compared. But in the new version of the ASP.NET5, it is bullish, Microsoft provides the Microsoft.Framework.Logging framework is the. NET version of the SLF4J, provide the appropriate interface, other third-party components can be implemented according to the interface.
Iloggerfactory interface
ILoggerFactory
An interface is an inbound point for a log, and an instance of the interface can be obtained through dependency injection in the system, and the log logger is created based on the example, ILogger
as shown in the following example:
var factory = ServiceProvider.GetRequiredService<ILoggerFactory>(); var logger1 = factory.CreateLogger(typeof(HomeController).FullName); //CreateLogger var logger2 = factory.CreateLogger<HomeController>(); //CreateLogger logger1.Log(LogLevel.Information, 1, null, null, null); // 日志记录 logger1.LogInformation("123"); // 扩展方法 logger1.LogError("123"); // 扩展方法
Alternatively, you can get the above example from the Loggerfactory parameter in the Startup.cs configure method.
ILoggerFactory
The interface is defined as follows:
public interface ILoggerFactory{ //日志最小记录级别 LogLevel MinimumLevel { get; set; } //创建日志记录实例 ILogger CreateLogger(string categoryName); //一般是根据功能模块或类名进行分类 void AddProvider(ILoggerProvider provider); // 添加日志记录provider(如第三方实现)}
In the implementation of this interface, we can set the minimum logging basic, with the following categories:
public enum LogLevel{ Debug = 1, Verbose = 2, Information = 3, Warning = 4, Error = 5, Critical = 6,}
You can also add provider for a third-party implementation, such as adding a console version of the implementation:
public static ILoggerFactory AddConsole(this ILoggerFactory factory){ factory.AddProvider(new ConsoleLoggerProvider((category, logLevel) => logLevel >= LogLevel.Information)); return factory;}
The logger instance is then created through the Createlogger method, and the log is finally logged.
Iloggerprovider and ILogger
All third-party implementations need to implement the Iloggerprovider interface and the ILogger interface, where the interface is simple, that is, to implement the method of creating the ILogger interface, the code is as follows:
public interface ILoggerProvider{ ILogger CreateLogger(string name); //创建给定类别的ILgger实例}
The implementation of ILogger is also relatively simple, in addition to implementing a common logging method, but also to implement a method of logging level judgment and a scope creation method, the interface is defined as follows:
public interface ILogger{ //支持大多数日志记录的通用方法,其它访问通过扩展方法进行完善 void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter); //判断是否可以记录给定的日志级别 bool IsEnabled(LogLevel logLevel); //开启一个逻辑操作作用域 IDisposable BeginScopeImpl(object state);}
Implement the above two interfaces, the method can be used to factory
AddProvider
add the provider to the instance, to achieve the purpose of logging. The current default implementation of ASP. NET 5 in the 4 logging provider, respectively: Console, NLog, Serilog, Trace, when registering these provider, you can use the extension method, the example is as follows:
loggerfactory.AddConsole()loggerfactory.AddNLog(new NLog.LogFactory())loggerfactory.AddSerilog(new LoggerConfiguration())var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");factory.AddTraceSource(testSwitch, new ConsoleTraceListener());
Extension methods for ILogger
To facilitate logging, Microsoft has Microsoft.Framework.Logging.LoggerExtensions
defined 6 extension methods in the following form for 6 levels of log records, as follows:
public static void LogInformation(this ILogger logger, string message)public static void LogInformation(this ILogger logger, int eventId, string message)public static void LogInformation(this ILogger logger, string format, params object[] args)public static void LogInformation(this ILogger logger, int eventId, string format, params object[] args)public static void LogInformation(this ILogger logger, ILogValues state, Exception error = null)public static void LogInformation(this ILogger logger, int eventId, ILogValues state, Exception error = null)// 其它Debug、Verbose、Warning、Error、Critical也都遵循LogXXXX()规则.
So when using it, we can use methods like Logdebug (), LogError () to quickly log logs. In addition, the class also has three levels for warning, Error, critical, and 2 extension methods, respectively, as shown in the following example:
public static void LogWarning(this ILogger logger, string message, Exception error)public static void LogWarning(this ILogger logger, int eventId, string message, Exception error)
Some of these extension methods are used to estimate that there is no rival in the world.
Summarize
With the interface-based programming mechanism and DI Dependency injection mechanism, we can easily implement the third-party log provider extension, thus logging to any place we want to record, such as a NoSQL database such as MongoDB.
Synchronization and recommendations
This article has been synchronized to the Catalog index: Interpreting ASP. & MVC6 Series
Interpreting ASP 5 & MVC6 Series (9): Log frame