.netcore入门32:asp.net core集成NLog

环境:

  • window10 x64
  • asp.net core 3.1
  • vs2019
  • NLog.Web.AspNetCore 4.9.3

一、准备aspnetcore webapi项目

新建一个webapi项目(工程名称:NLog-Trial)即可,略。

二、安装nuget包

<ItemGroup>
  <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />
ItemGroup>

三、在Programe.cs文件中配置NLog

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                //先清空所有的日志记录提供程序
                logging.ClearProviders();
                //使用微软提供的控制台输出
                logging.AddConsole();
                //引入NLog
                logging.AddNLog();
                //将NLog中的日志输出级别设置最低,这样所有的日志都会转发到NLog,然后由NLog进行二次过滤
                logging.AddFilter<NLogLoggerProvider>(level => level >= LogLevel.Trace);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

四、在项目目录下新建nlog.config文件

.netcore入门32:asp.net core集成NLog_第1张图片
nlog.config文件内容如下:


<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="${basedir}/logs/internal-nlog.txt">

	
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
	extensions>

	
	<targets>
		
		<target xsi:type="File" name="allfile" fileName="${basedir}/logs/nlog-all-${shortdate}.log"
				layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] ${message} ${exception:format=tostring}" />

		
		<target xsi:type="File" name="ownFile-web" fileName="${basedir}/logs/nlog-own-${shortdate}.log"
				layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] [url: ${aspnet-request-url}] [action: ${aspnet-mvc-action}] ${message} ${exception:format=tostring}" />

		
		<target xsi:type="File" name="seriousfile" fileName="${basedir}/logs/nlog-serious-${shortdate}.log"
				layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] ${message} ${exception:format=tostring}" />
	targets>


	<rules>
		
		<logger name="Microsoft.*" minlevel="Trace" writeTo="allfile" />
		<logger name="System.*" minlevel="Trace" writeTo="allfile" />

		
		<logger name="NLog_Trial.*" minlevel="Trace" writeTo="ownFile-web" />

		
		<logger name="*" minlevel="Warning" writeTo="seriousfile" />
	rules>
nlog>

五、在控制器中写入测试代码(WeatherForecastController.cs)

public class WeatherForecastController : ControllerBase
{
      private readonly ILogger<WeatherForecastController> _logger;
      public WeatherForecastController(ILogger<WeatherForecastController> logger)
      {
          _logger = logger;
      }
 	 //...
     [HttpGet]
     public IEnumerable<WeatherForecast> Get()
     {
         _logger.LogTrace("trace");
         _logger.LogDebug("debug");
         _logger.LogInformation("info");
         _logger.LogWarning("warn");
         _logger.LogError("error");
         _logger.LogCritical("critical");
         using (_logger.BeginScope("测试日志的Scope"))
         {
             _logger.LogTrace("scope-trace");
             _logger.LogDebug("scope-debug");
             _logger.LogInformation("scope-info");
             _logger.LogWarning("scope-warn");
             _logger.LogError("scope-error");
             _logger.LogCritical("scope-critical");
         }
         _logger.LogTrace("Scope已经结束了。。。");
         var rng = new Random();
         throw new Exception("测试异常日志");
         return Enumerable.Range(1, 5).Select(index => new WeatherForecast
         {
             Date = DateTime.Now.AddDays(index),
             TemperatureC = rng.Next(-20, 55),
             Summary = Summaries[rng.Next(Summaries.Length)]
         })
         .ToArray();
     }
     //...
}

六、运行查看效果

输出文件:
.netcore入门32:asp.net core集成NLog_第2张图片
文件内容:nlog-serious-2020-11-15
.netcore入门32:asp.net core集成NLog_第3张图片
.netcore入门32:asp.net core集成NLog_第4张图片
.netcore入门32:asp.net core集成NLog_第5张图片
.netcore入门32:asp.net core集成NLog_第6张图片

你可能感兴趣的:(c#,.net)