In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces ASP.NET Core how to add logging related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this ASP.NET Core how to add logging article, let's take a look.
1. Preface
ASP.NET Core supports logging API for a variety of built-in and third-party logging provider applications.
two。 Add log provider
Logging provides the application to display or store logs. For example, the console provider application displays logs on the console, and the Azure Application Insights provider application stores these logs in Azure Application Insights. To add a provider application, call the provider's Add {provider name} extension method in Program.cs:
Public static void Main (string [] args) {var webHost = new WebHostBuilder () .UseKestrel () .UseContentRoot (Directory.GetCurrentDirectory ()) .ConfigureAppConfiguration ((hostingContext, config) = > {var env = hostingContext.HostingEnvironment Config.AddJsonFile ("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile ($"appsettings. {env.EnvironmentName} .json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables () }) .ConfigureLogging ((hostingContext, logging) = > {/ / add Logging node configuration logging.AddConfiguration (hostingContext.Configuration.GetSection ("Logging")) for logs in appsettings.json; / / log console record provider logging.AddConsole (); / / log Debug record provider logging.AddDebug () / / logging EventSource recording provider logging.AddEventSourceLogger ();}) .UseStartup () .build (); webHost.Run ();}
The default project template calls CreateDefaultBuilder, which adds log records (console, DEBUG, EventSource) to the application:
Public static void Main (string [] args) {CreateWebHostBuilder (args). Build (). Run ();} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .UseStartup (); 3. Create a log
Create logs to get ILogger objects from dependency injection (DI). The following example Razor page creates a log with a level of Information and a category of AboutModel class (Models/AboutModel):
Public class AboutModel {private readonly ILogger _ logger; public AboutModel (ILogger logger) {/ / ILogger is the built-in logging component of Core, which has been injected by default. There is no need to manually inject _ logger = logger;} public void OnGet () {var Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString ()}"; _ logger.LogInformation ("Message displayed: {Message}", Message);} private readonly ILogger _ logger Public HomeController (ILogger logger) {_ logger = logger;} public IActionResult Index () {AboutModel aboutModel = new AboutModel (_ logger); aboutModel.OnGet (); return View ();}
Start debugging through the Kestral server:
Take a look at the console output logging:
The log "level" represents the severity of the logged event. The log Category is the string associated with each log. The ILogger instance creates a log with Category as the fully qualified name of type T.
3.1 create logs at startup (Startup)
To write the log to the Startup class, the constructor signature needs to include the ILogger parameter:
Public class Startup {private readonly ILogger _ logger; public Startup (IConfiguration configuration, ILogger logger) {Configuration = configuration; _ logger = logger;} public IConfiguration Configuration {get;} public void ConfigureServices (IServiceCollection services) {_ logger.LogInformation ("Added TodoRepository to services") } public void Configure (IApplicationBuilder app, IHostingEnvironment env) {if (env.IsDevelopment ()) {_ logger.LogInformation ("In Development environment");}
Start debugging through the Kestral server and take a look at the console output log record:
3.2 create logs in the program (Program)
If you use CreateDefaultBuilder, you can choose to provide the application to replace the default application. Call ClearProviders, and then add the desired application.
Public class Program {public static void Main (string [] args) {var host = CreateWebHostBuilder (args). Build (); var logger = host.Services.GetRequiredService (); logger.LogInformation ("Seeded the database."); host.Run ();} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .UseStartup () .ConfigureLogging (logging = > {logging.ClearProviders ()) Logging.AddConsole ();})
Start debugging through the Kestral server and take a look at the console output log record:
4.Configuration
The logging provider configuration is provided by one or more configuration providers:
File formats (INI, JSON, and XML).
Command line arguments.
Environment variable.
.net object in memory.
Unencrypted Secret Manager storage.
Encrypted user storage, such as Azure Key Vault.
Custom provider (installed or created).
For example, logging configuration is typically provided by the Logging section of the application settings file. The following example shows the contents of a typical appsettings.Development.json file:
{"Logging": {"LogLevel": {"Default": "Debug", "System": "Information", "Microsoft": "Information"}, "Console": {"IncludeScopes": true}}
The Logging property can have LogLevel and log provider properties (display console). The LogLevel property under Logging specifies the lowest level used to record the selected category. In this example, the System and Microsoft categories are recorded at the Information level, and the others are recorded at the Debug level. If the provider supports log scopes, IncludeScopes indicates whether these domains are enabled.
5. Log level
Each log specifies a LogLevelvalue. The log level indicates severity or importance. If the LogLevel is at the Warning level, the tracking Trace,Debug,Information level will not be logged. ASP.NET Core defines the following log levels, sorted by severity from lowest to highest:
Trace Trace = 0
Debug Debug = 1
Information Information = 2
Warning Warning = 3
Error Error = 4
Critical Critical = 5
6. Built-in logging provider
Console: logging.AddConsole (); dotnet run to view the console logging output.
Debug: logging.AddDebug (); in Linux, this provider writes logs to / var/log/message.
EventSource:logging.AddEventSourceLogger (); in Windows, it uses the PerfView utility to collect and view logs, but there is no event collection and display tool that supports Linux or macOS.
EventLog:logging.AddEventLog (); sends log output to the Windows event log.
TraceSource:logging.AddTraceSource (sourceSwitchName); the application must run on the .NET Framework (not the .NET Core).
7. Third-party logging provider
A third-party logging framework for ASP.NET Core. The link address is available in the official document:
Elmah.io (GitHub repository)
Gelf (GitHub repository)
JSNLog (GitHub repository)
KissLog.net (GitHub repository)
Loggr (GitHub repository)
NLog (GitHub repository)
Sentry (GitHub repository)
Serilog (GitHub repository)
Stackdriver (Github repository)
For example, using NLog:NLog is a flexible and free logging platform for a variety of .NET platforms, including .NET standards. NLog can easily write to multiple targets. (database, file, console) and instantly change the logging configuration.
This is the end of the article on "how to add logging in ASP.NET Core". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to add logging in ASP.NET Core". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.