Interpreting ASP.NET 5 & MVC6 Series (9): Logging Framework

Interpreting ASP.NET 5 & MVC6 Series (9): Logging Framework

Framework Introduction

In the previous .NET, Microsoft has not provided a decent logging framework. Some of the currently available frameworks, such as Log4Net, NLog, and CommonLogging, are more or less difficult to use and cannot be compared with Java's SLF4J. However, in the new version of ASP.NET 5, it is very powerful. The Microsoft.Framework.Logging framework set provided by Microsoft is the .NET version of SLF4J, providing corresponding interfaces, and other third-party components can implement their own implementations based on the interfaces.

ILoggerFactory Interface

The ILoggerFactory interface is the entry point for logs. You can get an instance of this interface through dependency injection in the system, and create a logger ILogger to record logs based on this example. The example is as follows:

var factory = ServiceProvider.GetRequiredService (); var logger1 = factory.CreateLogger(typeof(HomeController).FullName); //CreateLogger var logger2 = factory.CreateLogger (); //CreateLogger logger1.Log(LogLevel.Information, 1, null, null, null); // Logging logger1.LogInformation("123"); // Extension method logger1.LogError("123"); // Extension method

Alternatively, you can also get the above example from the loggerfactory parameter in the Configure method of Startup.cs. The definition of the ILoggerFactory interface is as follows:

  1. public   interface ILoggerFactory
  2. {
  3. //Minimum log level  
  4. LogLevel MinimumLevel { get; set; }
  5.  
  6. //Create a logging instance  
  7. ILogger CreateLogger(string categoryName); //Generally classified according to functional modules or class names  
  8.  
  9. void AddProvider(ILoggerProvider provider); // Add logging provider (such as third-party implementation)  
  10. }

In the implementation of this interface, we can set the minimum record base of the log, the categories are as follows

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

You can also add a third-party provider, such as a console version:

  1. public   static ILoggerFactory AddConsole( this ILoggerFactory factory)
  2. {
  3. factory.AddProvider( new ConsoleLoggerProvider((category, logLevel) => logLevel >= LogLevel.Information));
  4. return factory;
  5. }

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

ILoggerProvider and ILogger

All third-party implementations need to implement the ILoggerProvider interface and the ILogger interface. The interface is very simple, which is to implement the method of creating the ILogger interface. The code is as follows:

  1. public   interface ILoggerProvider
  2. {
  3. ILogger CreateLogger(string name); //Create an ILogger instance of a given category  
  4. }

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

  1. public   interface ILogger
  2. {
  3. //Supports most common logging methods, other accesses are improved through extension methods  
  4. void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func

After implementing the above two interfaces, you can add the provider to the instance through the factory's AddProvider method to achieve the purpose of logging. Currently, ASP.NET 5 implements four logging providers by default, namely: Console, NLog, Serilog, and Trace. When registering these providers, you can use extension methods. The examples are as follows:

  1. loggerfactory.AddConsole()
  2. loggerfactory.AddNLog( new NLog.LogFactory())
  3. loggerfactory.AddSerilog( new LoggerConfiguration())
  4. var testSwitch = new SourceSwitch( "TestSwitch" , "Level will be set to warning for this test" );
  5. factory.AddTraceSource(testSwitch, new ConsoleTraceListener());

Extension methods of ILogger

To facilitate logging, Microsoft has defined six extension methods for each of the six levels of logging in Microsoft.Framework.Logging.LoggerExtensions. The examples are as follows:

  1. public   static   void LogInformation( this ILogger logger, string message)
  2. public   static   void LogInformation( this ILogger logger, int eventId, string message)
  3. public   static   void LogInformation( this ILogger logger, string format, params object[] args)
  4. public   static   void LogInformation( this ILogger logger, int eventId, string format, params object[] args)
  5. public   static   void LogInformation( this ILogger logger, ILogValues ​​state, Exception error = null )
  6. public   static   void LogInformation( this ILogger logger, int eventId, ILogValues ​​state, Exception error = null )
  7.  
  8. // Other Debug, Verbose, Warning, Error, and Critical also follow the LogXXXX() rules.

So when using it, we can use methods like LogDebug() and LogError() to quickly record logs. In addition, this class also defines two extension methods for the three levels of Warning, Error, and Critical, as shown below:

  1. public   static   void LogWarning( this ILogger logger, string message, Exception error)
  2. public   static   void LogWarning( this ILogger logger, int eventId, string message, Exception error)

Some of these extension methods are probably invincible when used.

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 as to record the logs to any place we want, such as NoSQL databases such as MongoDB.

<<:  Interpreting ASP.NET 5 & MVC6 Series (8): Session and Caching

>>:  Interpreting ASP.NET 5 & MVC6 Series (10): Controller and Action

Recommend

The probability of iPhone 6 bending is only 0.00009%

Regarding the iPhone 6 bending scandal that has c...

Huh? Ducks can climb trees...

"Ding Dong Ding Dong..." The spring bre...

Allergy Revelation: Why are more and more people suffering from allergies?

© Buckhead Primary and Urgent Care Clinic Leviath...

Several tips on user packaging: How to become famous on Douyin?

The author of this article takes Douyin as an exa...

The takeaway beef has colored reflections. Is it bad? Can I still eat it?

Many people love to eat beef, such as beef ramen,...

8 types of operation tools to help you become an operation master

In the era of big data and AI , even pigs can fly...

The partridge commonly seen in ancient poems is actually a fighter!

Recently, the Forestry and Grassland Bureau of Me...

What sense of crisis should P2P online lending have?

At the end of the year, the development of the P2...