[英]Implement Logging Using Serilog In ASP.NET Core 5.0 Application With Database
在我的 asp.net core 5.0 应用程序中,每当我尝试使用 serilog 执行日志记录并将日志保存到我的数据库时。 但是,当我运行 api 时,它告诉我:
System.TypeInitializationException HResult=0x80131534 Message=“PaymentService.API.Program”的类型初始值设定项引发异常。 Source=PaymentService.API StackTrace:位于 API\\Program.cs 中的 PaymentService.API.Program.get_Configuration():第 21 行,位于 API\\Program.cs 中的 PaymentService.API.Program.Main(String[] args):第 34 行
这个异常最初是在这个调用堆栈上抛出的:[外部代码]
内部异常 1:FormatException:无法解析 JSON 文件。
内部异常 2:JsonReaderException:预期深度在 JSON 负载结束时为零。 有一个打开的 JSON 对象或数组应该关闭。 行号:7 | 字节位置内联:1。
第 21 行是:
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)
.Build();
第 34 行是:
string connectionString = Configuration.GetConnectionString("Default");
我是新手,但我是否必须对“ASPNETCORE_ENVIRONMENT”进行任何配置?
在那之后,我试图添加自定义列到一个名为数据库CorrelationId
并发送CorrelationId
的其特定的列。 我是按照本教程来这样做的,但是我卡在了他们想要为日志捕获用户的步骤上。 我想做同样的事情,但对日志使用CorrelationId
。
Program.cs
:
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)
.Build();
public static void Main(string[] args)
{
string connectionString = Configuration.GetConnectionString("Default");
var columnOptions = new ColumnOptions
{
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn("CorrelationId", SqlDbType.NVarChar)
}
}; // through this columnsOptions we can dynamically add custom columns which we want to add in the db
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.MSSqlServer(connectionString, sinkOptions: new MSSqlServerSinkOptions { TableName = "PaymentLogs" }
, null, null, LogEventLevel.Information, null, columnOptions: columnOptions, null, null)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseSerilog();
});
}
Startup.cs
:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "PaymentService.API", Version = "v1" });
});
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<LogHeaderMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PaymentService.API v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
/* app.Use(async (httpContext, next) =>
{
var correlationId = httpContext.Session. // need to find a way to map correlationId and send it to the logs
})*/
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
appsettings.json
{
"ConnectionStrings": {
"Default": "Data Source=.\\SQLExpress;Database=ElasticSearchService;Trusted_Connection=True;"
},
"Serilog": {
"MinimumLevel": "Information",
"AllowedHosts": "*"
}
PaymentController
[Route("api/[controller]")]
[ApiController]
public class PaymentController : ControllerBase
{
private readonly ILogger<PaymentServicesController> _logger;
public PaymentServicesController(ILogger<PaymentServicesController> logger)
{
_logger = logger;
}
// GET: api/<PaymentServices>
[HttpGet]
[Route("payment")]
public void MakePayment()
{
_logger.LogInformation("PAYMENT METHOD INVOLKED!!!");
}
}
这里的header
将保存我需要的correlationId
,以便我可以将它发送到数据库。
public class LogHeaderMiddleware
{
private readonly RequestDelegate _next;
public LogHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var header = context.Request.Headers["CorrelationId"];
if (header.Count > 0)
{
var logger = context.RequestServices.GetRequiredService<ILogger<LogHeaderMiddleware>>();
using (logger.BeginScope("{@CorrelationId}", header[0]))
{
await _next(context);
}
}
else
{
await _next(context);
}
}
}
您在 JSON 文件中缺少 Serilog 对象的右括号,导致 JSON 格式错误。 因此出现异常:内部异常 1: FormatException: 无法解析 JSON 文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.