Skip to content

Instantly share code, notes, and snippets.

@doggy8088
Created November 29, 2021 16:48
Show Gist options
  • Save doggy8088/32f7c179f06ab0616b2e32728f734c5b to your computer and use it in GitHub Desktop.
Save doggy8088/32f7c179f06ab0616b2e32728f734c5b to your computer and use it in GitHub Desktop.
Serilog 與 ASP.NET Core 6.0 範例
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning"
}
},
"Enrich": [ "FromLogContext" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "./logs/log-.json",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
},
"AllowedHosts": "*"
}
using Serilog;
using Serilog.Events;
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
try
{
Log.Information("Starting web host");
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.WebHost.UseSerilog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseSerilogRequestLogging(options =>
{
// 如果要自訂訊息的範本格式,可以修改這裡,但修改後並不會影響結構化記錄的屬性
options.MessageTemplate = "Handled {RequestPath}";
// 預設輸出的紀錄等級為 Information,你可以在此修改記錄等級
// options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
// 你可以從 httpContext 取得 HttpContext 下所有可以取得的資訊!
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("UserID", httpContext.User.Identity?.Name);
};
});
app.UseAuthorization();
app.MapControllers();
app.Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace serilogdemo2.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IDiagnosticContext _diagnosticContext;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IDiagnosticContext diagnosticContext)
{
_logger = logger;
_diagnosticContext = diagnosticContext;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_diagnosticContext.Set("UserID", User.Identity?.Name);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment