Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How ASP.NET Core uses NLog to log

2025-04-11 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 use NLog to record logs, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

I. Preface

In all applications, the log function is an indispensable module. We can debug according to the log information and view the resulting error messages. In ASP.NET Core, we can use log4net or NLog log components to achieve the logging function. Here we explain how to use NLog in ASP.NET Core.

The .NET Core 3.1 is used here to create the application.

So what is NLog?

NLog is a class library based on the .NET platform, we can use NLog to add perfect tracking debugging code in the application.

NLog is a simple and flexible .NET logging class library. By using NLog, we can output debug diagnostics with context in any .NET language, configure the style of the output according to individual preferences, and then send it to one or more output targets (target).

NLog's API is very similar to log4net, and the configuration is very simple. NLog is configured using a routing table, which makes the NLog configuration file easy to read and easy to maintain in the future.

NLog follows BSD license, which allows commercial applications and fully open source code. Anyone can use it for free, test it, and then feedback questions and suggestions through the mailing list.

NLog supports .NET, Candlestick +, and COM components, so our programs, components, including legacy modules written in C++/COM, can send information to NLog through the same routing engine.

In a nutshell, NLog is the component used to log a project.

Second, use NLog

First, let's create a WebAPI project:

1. Introduce NLog

Search for NLog.Web.AspNetCore directly in NuGet, and then install it, as shown below:

After the installation is complete, you can see it in the dependencies:

Modify the Program class and configure it to use NLog. The code is as follows:

Using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Hosting;using NLog.Web;namespace NLogDemo {public class Program {public static void Main (string [] args) {CreateHostBuilder (args) .Build () .Run () } public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .ConfigureWebHostDefaults (webBuilder = > {webBuilder.UseStartup ();}) / / configure to use NLog .UseNog ();}} 2, add configuration file

Right-click to add the new item, then select Web configuration file, and name it nlog.config, as shown in the following figure:

The nlog.config file structure is as follows:

After adding the configuration file, we also need to modify the properties of the configuration file to always copy, as shown in the following figure:

3. Use in the controller

With the above steps, we have completed the configuration of NLog, and then we can use it in the controller to achieve injection through constructor injection. The controller code is as follows:

Using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace NLogDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class NLogTestController: ControllerBase {private readonly ILogger _ logger; public NLogTestController (ILogger logger) {_ logger = logger;} [HttpGet] public IActionResult Get () {_ logger.LogError ("this is an error message") _ logger.LogDebug ("this is debug information"); _ logger.LogInformation ("this is prompt information"); return Ok ();}

Run the program, access the nlogtest controller, and check to see if there is log generation:

The file path we configured in nlog.config is D:\ Log. From the screenshot above, we can see that a log has been generated. Two log files are generated here because we have configured different log levels in nlog.config. The contents of the log are as follows:

You can see that the Microsoft log is also output during startup. If you do not want to output the Microsoft log, you can modify the order of path rules under the rules node in nlog.config.

4. Read the configuration file of the specified location

In the above example, we add the nlog.config file directly under the root directory of the project, and sometimes we want to put all the configuration files in the program into a separate folder, which is easy to manage, so how to set up the nlog.config file that allows the program to read the specified location? Look at the following example.

Create a new folder, name it XmlConfig, and then move the nlog.config file to the XmlConfig folder. The structure after moving to this folder is shown below:

Then modify the Program file and set it to read the nlog.config file under the XmlConfig folder in the program as follows:

Using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Hosting;using NLog.Web;namespace NLogDemo {public class Program {public static void Main (string [] args) {/ / set to read the nlog.config file NLogBuilder.ConfigureNLog ("XmlConfig/nlog.config") at the specified location; CreateHostBuilder (args) .Build () .Run () } public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .ConfigureWebHostDefaults (webBuilder = > {webBuilder.UseStartup ();}) / / configure to use NLog .UseNog ();}}

This allows you to read the configuration file under the XmlConfig folder.

5. Encapsulation

In the above example, the final output log format is based on the layout style output in the nlog.config configuration file, sometimes the output may not meet our needs, we can encapsulate the log function module in the program and output the log format defined by ourselves.

Add a class library to the solution, name it Nlog.Framework, and then add a Log folder in the class library to put all Log-related files under this folder. The added project structure is shown in the following figure:

Add the LogMessage class, which contains some information attribute fields to be recorded:

Using System;namespace Nlog.Framework.Log {/ IP message / public class LogMessage {/ IP / public string IpAddress {get; set;} / operator / public string OperationName {get; set } / Operation time / public DateTime OperationTime {get; set;} / public string LogInfo {get; set;} / tracking information / public string StackTrace {get; set;}

Add a formatting class to format the log output:

Using System.Text;namespace Nlog.Framework.Log {/ format output style / public class LogFormat {public static string ErrorFormat (LogMessage logMessage) {StringBuilder strInfo = new StringBuilder (); strInfo.Append ("1. Operation time: "+ logMessage.OperationTime +"\ r\ n "); strInfo.Append (" 2. Operator: "+ logMessage.OperationName +"\ r\ n "); strInfo.Append (" 3. Ip: "+ logMessage.IpAddress +"\ r\ n "); strInfo.Append (" 4. Error content: "+ logMessage.LogInfo +"\ r\ n "); strInfo.Append (" 5. Tracking: "+ logMessage.StackTrace +"\ r\ n ") StrInfo.Append ("- -\ r\ n ") Return strInfo.ToString ();}

Dependency injection is used here, so let's first define an interface with the following code:

Using System;namespace Nlog.Framework.Log {public interface INLogHelper {void LogError (Exception ex);}}

Then define the implementation class of the interface, as follows:

Using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Logging;using System;namespace Nlog.Framework.Log {public class NLogHelper: INLogHelper {/ / public static Logger logger {get; private set;} private readonly IHttpContextAccessor _ httpContextAccessor; private readonly ILogger _ logger; public NLogHelper (IHttpContextAccessor httpContextAccessor, ILogger logger) {_ httpContextAccessor = httpContextAccessor; _ logger = logger } public void LogError (Exception ex) {LogMessage logMessage = new LogMessage (); logMessage.IpAddress = _ httpContextAccessor.HttpContext.Request.Host.Host; if (ex.InnerException! = null) logMessage.LogInfo = ex.InnerException.Message; else logMessage.LogInfo = ex.Message; logMessage.StackTrace = ex.StackTrace LogMessage.OperationTime = DateTime.Now; logMessage.OperationName = "admin"; _ logger.LogError (LogFormat.ErrorFormat (logMessage));}

To demonstrate the effect, let's add a global exception filter with the following code:

Using Microsoft.AspNetCore.Mvc.Filters;using Nlog.Framework.Log;using System.Threading.Tasks;namespace NLogDemo.Filter {/ Asynchronous version Custom Global exception filter / public class CustomerGlobalExceptionFilterAsync: IAsyncExceptionFilter {private readonly INLogHelper _ logHelper; public CustomerGlobalExceptionFilterAsync (INLogHelper logHelper) {_ logHelper = logHelper } / re-OnExceptionAsync method / exception information / public Task OnExceptionAsync (ExceptionContext context) {/ / if the exception is not handled Then process if (context.ExceptionHandled = = false) {/ / record error message _ logHelper.LogError (context.Exception) / / set to true, indicating that the exception has been handled, and context.ExceptionHandled = true;} return Task.CompletedTask;}} will not be handled in other places where the exception is caught.

Then add a controller to simulate the error operation in the controller, as follows:

Using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace NLogDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {/ log / private readonly ILogger _ logger; public ValuesController (ILogger logger) {_ logger = logger } [HttpGet] public IActionResult Test () {_ logger.LogError ("Test Encapsulation log"); int I = 0; int result = 10 / i; return Ok ();}

Modify the Program class:

Using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Hosting;using NLog;using NLog.Web;using System;namespace NLogDemo {public class Program {public static void Main (string [] args) {/ / read the configuration file var logger = NLogBuilder.ConfigureNLog ("XmlConfig/nlog.config") .GetCurrentClassLogger () at the specified location Try {logger.Info ("Init Main"); CreateHostBuilder (args). Build (). Run ();} catch (Exception ex) {logger.Error (ex, "Stopped program because of exception") } finally {LogManager.Shutdown ();}} public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .ConfigureWebHostDefaults (webBuilder = > {webBuilder.UseStartup ()) }) / / configure to use NLog .UseNLog ();}}

Finally, inject into the Startup class:

Public void ConfigureServices (IServiceCollection services) {# region add exception handling filter services.AddControllers (options = > options.Filters.Add (typeof (CustomerGlobalExceptionFilterAsync); # endregion services.AddSingleton (); services.AddSingleton (); / / NLogHelper.LoadLogger (); services.AddControllers ();}

This completes a simple encapsulation, runs the program, and accesses the value controller test:

In the above example, only Error is encapsulated, and if it is a log of other levels, it can be encapsulated by itself.

Thank you for reading this article carefully. I hope the article "how ASP.NET Core uses NLog to record logs" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report