nuget
dotnet add package Serilog.AspNetCore
配置Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Snblog
{
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Enrich.FromLogContext()
.CreateLogger();
try
{
Log.Information("启动主机");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "主机意外终止");
}
finally
{
Log.CloseAndFlush();
}
//CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog() // <-添加此行
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
配置appsettings.json
//"Logging": {
// "LogLevel": {
// "Default": "Information",
// "Microsoft": "Warning",
// "Microsoft.Hosting.Lifetime": "Information"
// }
//},
//注释以上
//增加以下
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": ".\\LogFiles\\log.txt",
"rollingInterval": "Day",
//"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
// "outputTemplate": "Occurrence Time: {Timestamp:HH:mm:ss.fff} Level: {Level} Detailed Information: {Message}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
},
在控制器使用
private readonly ILogger < SnArticleController > logger;
public SnArticleController(ILogger < SnArticleController > logger)
{
this.logger = logger ? ?
throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// 查询总数 (缓存)
/// </summary>
[HttpGet("GetArticleCount")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public IActionResult GetArticleCount()
{
logger.LogInformation("启动{ActionName}", "获取所有待办事项"); // <-添加此行
return Ok(_service.GetArticleCount());
}