.net core中使用nlog替代默认日志

1、添加引用nlog.config和Nlog.Web.AspNetCore

 

 

 2、配置NLog 配置文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <!--此部分中的所有目标将自动异步-->
    <target name="asyncFile" xsi:type="AsyncWrapper">
      <!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
      <target name="log_file" xsi:type="File"
              fileName="${basedir}/ProjectLogs/${shortdate}/${logger}-${level}-${shortdate}.txt"
              layout="${longdate} | ${message} ${onexception:${exception:format=message} ${newline} ${stacktrace} ${newline}"
              archiveFileName="${basedir}/archives/${logger}-${level}-${shortdate}-{#####}.txt"
              archiveAboveSize="102400"
              archiveNumbering="Sequence"
              concurrentWrites="true"
              keepFileOpen="false" />
    </target>
    <!--使用可自定义的着色将日志消息写入控制台-->
    <target name="colorConsole" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" />
  </targets>

  <!--规则配置,final - 最终规则匹配后不处理任何规则-->
  <rules>
    <logger name="Microsoft.*" minlevel="Info" writeTo="" final="true" />
    <logger name="*" minlevel="Info" writeTo="asyncFile" />
    <logger name="*" minlevel="Warn" writeTo="colorConsole" />
  </rules>
</nlog>

3. 修改配置program

  public class Program
     {
         public static void Main(string[] args)
         {
             CreateHostBuilder(args).Build().Run();
 
             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)
                 .ConfigureWebHostDefaults(webBuilder =>
                 {
                     webBuilder.UseStartup<Startup>();
                 }).ConfigureLogging(logging =>
                 {
                     logging.ClearProviders(); // 这个方法会清空所有控制台的输出
                     logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                 })
                 .UseNLog(); // 使用NLog;
     }

 

posted on 2022-10-02 09:36  静以修身俭以养德  阅读(153)  评论(0编辑  收藏  举报

导航