簡體   English   中英

在帶有數據庫的 ASP.NET Core 5.0 應用程序中使用 Serilog 實現日志記錄

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM