如何使用 dotnet serilog 在日志中添加经过的时间?

问题描述 投票:0回答:1

我有一个网络应用程序。我想使用记录器记录服务的响应。

public class PrivacyModel : PageModel
{
    private readonly ILogger<PrivacyModel> _logger;
    private readonly MyService _service;

    public PrivacyModel(ILogger<PrivacyModel> logger, MyService service)
    {
        _logger = logger;
        _service = service;
    }

    public void OnGet(string question)
    {
        var answer = service.Execute(question);
        _logger.LogInformation("{@a}", answer);
    }
}

serilog 记录此信息。并将 api 执行经过的时间日志写入新的日志行。

[12:01:43 INF] Starting web application
[12:01:44 INF] Now listening on: http://localhost:5000
[12:01:44 INF] Application started. Press Ctrl+C to shut down.
[12:01:44 INF] Hosting environment: Development
[12:01:44 INF] Content root path: serilog-aspnetcore/samples/Sample
[12:01:47 WRN] Failed to determine the https port for redirect.
[12:01:47 INF] { "answer": "hello" }
[12:01:47 INF] HTTP GET / responded 200 in 95.0581 ms

我正在将日志添加到elasticsearch 和grafana。所以我需要在同一个 json 中加入操作执行的经过时间和应答响应。

我可以使用serilog丰富或其他方式加入吗?

c# .net-core serilog
1个回答
0
投票
using Serilog.Core;
using Serilog.Events;
using System;

// Custom enricher:

public class ElapsedTimeEnricher : ILogEventEnricher
{
    private readonly string _propertyName;
    private readonly DateTime _startTime;

    public ElapsedTimeEnricher(string propertyName = "ElapsedTime")
    {
        _propertyName = propertyName;
        _startTime = DateTime.UtcNow;
    }

    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var elapsed = DateTime.UtcNow - _startTime;
        var elapsedSeconds = elapsed.TotalSeconds;

        var elapsedProperty = new LogEventProperty(_propertyName, new ScalarValue(elapsedSeconds));
        logEvent.AddPropertyIfAbsent(elapsedProperty);
    }
}

// Configure Serilog to use the custom enricher:

Log.Logger = new LoggerConfiguration()
    .Enrich.With(new ElapsedTimeEnricher())
    .WriteTo.Console()
    .CreateLogger();

// Example usage
Log.Information("Application started");

// Your application logic
// ...

Log.Information("Application ended");

Log.CloseAndFlush();
© www.soinside.com 2019 - 2024. All rights reserved.