ASP.NET Core supports logging APIs for a wide range of built-in and third-party logging providers. Logging is an essential feature in our daily development.
Let's take a look at the renderings of the console first, as follows:
Add a log provider
Logging providers display or store logs. For example, a console provider displays logs on the console, and the Azure Application Insights provider stores these logs in Azure Application Insights. Logs can be sent to multiple destinations by adding multiple providers.
Edit the Program file as follows:
Create a log (constructor injection)
The following controller example creates logs at all levels.
Log level | Show text | Foreground color | Background color | Trace | trce | Gray | Black | Debug | dbug | Gray | Black | Information | info | DarkGreen | Black | Warning | warn | Yellow | Black | Error | fail | Red | Black | Critical | crit | White | Red |
Reference links:The hyperlink login is visible.
Run the project with the following command, and you can see the output log through the console.
Visit the local URL to see the output.
Control log level
We notDon't want to see the console output so many nonsensical info logs, I just want to see the important logs I recorded, what should I do?
1: Control the log level through the configuration file and edit appsettings.json file as follows:
This JSON will create 6 filtering rules: 1 for debugging providers, 4 for console providers, and 1 for all providers. When you create an ILogger object, choose a rule for each provider.
2: Pass code control (no testing)
The second AddFilter uses the type name to specify the debug provider. The first AddFilter applies to all providers because it does not specify the provider type.
Default minimum level
The minimum level setting takes effect only if the rules in the configuration or code do not apply to a given provider and category. The following example shows how to set the minimum level:
If the minimum level is not explicitly set, the default value is Information, which it representsTrace and Debug logs will be ignored。
Reference links:The hyperlink login is visible.
Use Autofac to inject ILogger logs via properties
Generally, we inject log services through constructors, how do we inject through attributes? How else to host ILogger to Autofac?
In the Startup editing method ConfigureServices, as follows:
The following four important sentences:
Be sure to add itloggerFactory.AddConsole();This line of code, otherwise the console willNothing is output, and autofac hosting, the configuration file will be invalid.
Controller Code:
Access the URL, dotnet run starts the project, and the console output is as follows:
How to inject logs ILogger into other classes through properties.
(End)
|