Interpreting ASP. NET 5 & MVC6 series tutorials (9): log framework, interpreting ASP. NET

Source: Internet
Author: User

Interpreting ASP. NET 5 & MVC6 series tutorials (9): log framework, interpreting ASP. NET

Framework Introduction

In the previous. NET, Microsoft has not yet provided a decent log framework. Currently, some frameworks that can be used, such as Log4Net, NLog, and CommonLogging, are more or less difficult to use, and cannot be compared with SLF4J of java. However, in the new ASP. in NET5, It is cool, Microsoft. framework. the Logging framework set is.. NET SLF4J provides corresponding interfaces. other third-party components can implement their own implementations based on the interfaces.

ILoggerFactory Interface

ILoggerFactoryThe interface is the log entry point. You can obtain the instance of this interface through dependency injection in the system, and create a logger according to this example.ILoggerTo record logs, for 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); // logger1.LogInformation ("123"); // The Extension Method logger1.LogError ("123"); // The Extension Method

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

ILoggerFactoryThe interface is defined as follows:

Public interface ILoggerFactory {// minimum logging level LogLevel MinimumLevel {get; set;} // create a logging instance ILogger CreateLogger (string categoryName ); // generally, void AddProvider (ILoggerProvider provider) is classified based on the function module or class name; // Add a logging provider (such as a third-party implementation )}

In the implementation of this interface, we can set the basic minimum log record, its category is as follows:

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

You can also add third-party providers, such as the implementation of adding a console version:

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

Create a logger instance using the CreateLogger method, and then record the log.

ILoggerProvider and ILogger

All third-party implementations must implement the ILoggerProvider interface and ILogger interface. The interface is very simple, that is, the method for creating the ILogger interface. The Code is as follows:

Public interface ILoggerProvider {ILogger CreateLogger (string name); // create an ILgger instance of a given category}

The implementation of ILogger is relatively simple. In addition to implementing common logging methods, you also need to implement a log-level judgment method and a scope creation method. The interface definition is as follows:

Public interface ILogger {// supports common methods for most Log records. Other access methods are used to improve void Log (LogLevel logLevel, int eventId, object state, Exception exception, Func <object, exception, string> formatter); // determines whether a given Log Level bool IsEnabled (LogLevel logLevel) can be recorded; // enable a logical operation scope: IDisposable BeginScopeImpl (object state );}

You can usefactoryOfAddProviderMethod to add the provider to the instance to record logs. ASP. NET 5 currently implements the logging Provider in 4 by default, namely Console, NLog, Serilog, and Trace. You can use the extension method when registering these providers. 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());

ILogger Extension Method

To facilitate logging, MicrosoftMicrosoft.Framework.Logging.LoggerExtensionsFor each of the six levels of log records, six extension methods are defined 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) // other Debug, Verbose, Warning, Error, and Critical rules also follow the LogXXXX () Rules.

Therefore, you can use methods such as LogDebug () and LogError () to quickly record logs. In addition, this class has three levels: Warning, Error, and Critical, and two extension methods are defined respectively. The example is 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 can be used, and it is estimated that they are no match in the world.

Summary

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.