netCore中的内置日志的使用
1、net Core 3.1 中配置
参考链接: https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace GDC.OfficeCloud.WebPC { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); //主要是配置这里 logging.AddConsole(); //主要是配置这里 }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel((context, options) => { //设置应用服务器Kestrel请求体最大为500MB options.Limits.MaxRequestBodySize = 524288000; }); webBuilder.UseStartup<Startup>(); }); } }
使用:
public class GDCActionFilter : IActionFilter { private readonly ILogger _logger; private IHostingEnvironment _environment; public GDCActionFilter(ILogger<GDCActionFilter> logger,IHostingEnvironment environment) { _logger = logger; _environment= environment; } public void OnActionExecuting(ActionExecutingContext context) { _logger.LogInformation("Request: {0} {1}", context.HttpContext.Request.Method, context.HttpContext.Request.Path);//只截取了部分代码
_logger.LogInformation("Request Body: {0}", context.HttpContext.Request.Body); //只截取了部分代码
查看日志:
这是在 Visual Studio调试中看到的,暂时没想到如何配置记录在 txt文件中
2、net 6.0以上的版本
参考:https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0
var builder = WebApplication.CreateBuilder(args); builder.Logging.ClearProviders(); //核心代码 builder.Logging.AddConsole(); //核心代码 builder.Services.AddRazorPages(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run();
或者如下方式配置:
var builder = WebApplication.CreateBuilder(); builder.Host.ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); });
使用:
public class AboutModel : PageModel { private readonly ILogger _logger; public AboutModel(ILogger<AboutModel> logger) { _logger = logger; } public void OnGet() { _logger.LogInformation("About page visited at {DT}", DateTime.UtcNow.ToLongTimeString()); } }
暂时没想到如何配置内置的日志到txt中。如果要实现记录到 txt中,可以使用第三方的 Nlog将日志输出到文件