1、Nuget添加Serilog.AspNetCore

2、Startup.cs添加如下代码

public void ConfigureServices(IServiceCollection services)
{

  //使用serilog替换自带的log实现
  Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
    .MinimumLevel.Debug()
    .Enrich.FromLogContext()
    .WriteTo.Console(new RenderedCompactJsonFormatter())
    .WriteTo.File(formatter: new CompactJsonFormatter(), "logs/mylog.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

  services.AddControllersWithViews();
}

3、Program.cs添加如下代码

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseSerilog(dispose: true);

4、调用

public class HomeController : Controller
    {
     //构造函数注入
private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("我能成功"); return View(); } }

5、亲测有效