跳转到内容

ASP.NET/logging

维基教科书,自由的教学读本

以ASP.NET MVC Core为例。

在Program.cs中,

 public static IHostBuilder CreateHostBuilder(string[] args) =>
   Host.CreateDefaultBuilder(args)

CreateDefaultBuilder的源代码已经做了(即内建了):

 .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).

所以不需要手工定义providers。如果想使用别的providers,需要如此:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logBuilder =>
                {
                   logBuilder.ClearProviders(); // removes all providers from LoggerFactory
                   logBuilder.AddConsole();
                   logBuilder.AddTraceSource("Information, ActivityTracing"); // Add Trace listener provider
                }) 
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

如果记日志到文件中,需要安装nuget包 Serilog.Extensions.Logging.File

然后在Startup.cs中,增加:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{
    // other code remove for clarity 
    loggerFactory.AddFile("Logs/mylog-{Date}.txt");
}

以HomeController为例,如下记日志:

namespace AspDotNetCoreMvcApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger<HomeController> logger){
            _logger = logger;
        }
        
        public IActionResult Index()
        {
            _logger.LogInformation("Log message in the Index() method");

            return View();
        }

        public IActionResult About()
        {
            _logger.LogInformation("Log message in the About() method");
            
            return View();
        }
    }
}

Microsoft.Extensions.Logging命名空间定义了日志级别和扩展方法:

日志级别和扩展方法
枚举名字 枚举值 ILogger扩展方法
Trace 0 LogTrace
Debug 1 LogDebug
Information 2 LogInformation
Warning 3 LogWarning
Error 4 LogError
Critical 5 LogCritical
None 6

在appsettings.json中,可定义日志的级别:

// appsettings.json
{
  "Logging": {
    "LogLevel": { // All providers
      "Default": "Information",
      "Microsoft": "Warning"
    }
    "Console": {
      "LogLevel": { // Console provider
        "Default": "Information", // Overrides preceding LogLevel:Default setting.
        "Microsoft": "Trace" // Writes at Trace Level inside the Microsoft assembly
      }        
    }
  }
}