Interpretation of ASP. NET 5 MVC 6 Series Tutorials (9): Logging Framework

  • 2021-07-26 07:30:06
  • OfStack

Introduction to the Framework

In the previous. NET, Microsoft has not provided a decent logging framework, and some frameworks that can be used at present, such as Log4Net, NLog and CommonLogging, are more or less difficult to use, which cannot be compared with SLF4J of java at all. However, in the new version of ASP. NET5, it can be described as bullish, and the framework set of Microsoft. Framework. Logging provided by Microsoft can be described as NET version of SLF4J, which provides corresponding interfaces, and other third-party components can realize their own implementation according to the interfaces.

ILoggerFactory interface

ILoggerFactory Interface is the entry point of logs, and an instance of this interface can be obtained through dependency injection in the system, and a logger can be created according to this example ILogger To log, an example is as follows:


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); //  Logging 
 logger1.LogInformation("123"); //  Extension method 
 logger1.LogError("123"); //  Extension method 

Alternatively, you can get the above example from the loggerfactory parameter in the Configure method of Startup. cs.

ILoggerFactory The interface is defined as follows:


public interface ILoggerFactory
{
 // Minimum log level 
 LogLevel MinimumLevel { get; set; }

 // Create a logging instance 
 ILogger CreateLogger(string categoryName); //1 Generally, it is classified according to functional module or class name 

 void AddProvider(ILoggerProvider provider); //  Add logging provider (For example 3 Party implementation) 
}

In the implementation of this interface, we can set the minimum record base of the log, which is classified as follows:


public enum LogLevel
{
 Debug = 1,
 Verbose = 2,
 Information = 3,
 Warning = 4,
 Error = 5,
 Critical = 6,
}

You can also add a third-party implementation of Provider, 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;
}

Then create a logger instance through the CreateLogger method, and finally log.

ILoggerProvider and ILogger

All third-party implementations need to implement ILoggerProvider interface and ILogger interface, in which the interface is very simple, that is, the method of creating ILogger interface can be realized, and the code is as follows:


public interface ILoggerProvider
{
 ILogger CreateLogger(string name); // Object for a given category ILgger Instances 
}

The implementation of ILogger is relatively simple. In addition to the general logging method, it is also necessary to implement a log level judgment method and a scope creation method. The interface definition is as follows:


public interface ILogger
{
 // Most common methods of logging are supported, and other access is improved by extending methods 
 void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter);

 // Determine whether a given log level can be recorded 
 bool IsEnabled(LogLevel logLevel);

 // Open 1 Logical operation scope 
 IDisposable BeginScopeImpl(object state);
}

The above two interfaces are implemented, which can be passed through factory Adj. AddProvider Method, add the provider to the instance for logging purposes. The current default in ASP. NET 5 implements the logging Provider in 4, which are Console, NLog, Serilog and Trace. When registering these Provider, you can use extension methods. Examples are 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 Method of ILogger

For the convenience of logging, Microsoft Microsoft.Framework.Logging.LoggerExtensions For each of the six levels of logging, six extension methods are defined in the following form, with examples 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)

//  Others Debug , Verbose , Warning , Error , Critical Also follow LogXXXX() Rules .

So when we use it, we can use methods like LogDebug () and LogError () to log quickly. In addition, the class also has three levels of Warning, Error and Critical, and two extension methods are defined respectively, as follows:


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, when used, are estimated to be invincible all over the world.

Summarize

Through the interface-based programming mechanism and DI dependency injection mechanism, we can easily implement the extension of the third-party log provider, so that we can record the log anywhere we want, such as MongoDB and other NoSQL databases.


Related articles: