使用依赖注入从 serilog .Net Core Web API 读取 InMemory 日志

问题描述

目标是读取此会话中添加到 serilog 的所有日志并传回给客户端,即使是从内部程序集的日志中(内部程序集也有用于捕获错误和所需信息的 serilog)

尝试使用“Serilog.Sinks.InMemory”读取,但对于依赖注入项目失败。但是当我们在同一个类中创建记录器时同样的工作

请参考下面的代码并帮助我找出可能是什么错误

基本细节, 应用:.Net Core Web Api 版本:核心 3.1

我遵循的步骤,

  1. 安装包Serilog.Sinks.InMemory
  2. appsettings.json
  "Logging": {
    "LogLevel": {
      "Default": "information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "information"
    }
  },"AllowedHosts": "*","Serilog": {
    "Using": ["Serilog.Sinks.File","NewRelic.LogEnrichers.Serilog","Serilog.Sinks.InMemory"],"MinimumLevel": {
      "Default": "information","Override": {
        "Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Warning"
      }
    },"Enrich": ["WithNewRelicLogsInContext"],"Writeto": [
      {
        "Name": "File","Args": {
          "formatter": "NewRelic.LogEnrichers.Serilog.NewRelicFormatter,NewRelic.LogEnrichers.Serilog","path": "xxx","rollingInterval": "Day","fileSizeLimitBytes": "20971520","rollOnFileSizeLimit": "true"
        }
      }
    ]
  }
} 
  1. Program.cs

    的 LoggerConfiguration 中添加了 InMemory Sink
     public static void Main(string[] args)
     {
         var configuration = new ConfigurationBuilder()
             .AddJsonFile("appsettings.json")
             .Build();
    
         Log.Logger = new LoggerConfiguration()
             .ReadFrom.Configuration(configuration)
             .Writeto.InMemory()
             .CreateLogger();
    
         CreateHostBuilder(args).Build().Run();
     }
    
  2. Controller.cs

public class ConvertionController: ControllerBase
    {
        private readonly ILogger<ConvertionController> _logger;
        private readonly IConversion _conversion;

        public ConvertionController(ILogger<ConvertionController> logger,IConversion conversion)
        {
            _logger = logger;
            _conversion = conversion;
        }

        [HttpPost]
        public virtual async Task<ActionResult> Post([FromForm]RequestModel request)
        {
                _logger.Loginformation($"Input Parameters : {JsonConvert.SerializeObject(request)}");
                try
                {
                    _logger.Loginformation($"Process started at : {DateTime.Now}");
                    var result = _conversion.convert(request);
                    _logger.Loginformation($"Process completed at : {DateTime.Now}");
                    return result;
                }
                catch(Exception ex)
                {
                     _logger.LogError(ex,"Conversion Failed:");
                    
                }
                finally
                {
                     //Goal is to read all the log added to serilog in this session,even from '_conversion' assembly's log (Conversion too have serilog for error and required information)

                     // Tried to read using following code but it fails. But same working when we create                                           
                     // the logger in same class
                     //var loglist = Serilog.Sinks.InMemory.InMemorySink.Instance.LogEvents;
                     //All the logs should pass back to client as headers
                     Response.Headers.Add("Serviceinformation","All the serilog logs as json string");
                }
        }
    }

建议阅读当前会话的 Serilog 日志(信息/错误/警告)

提前致谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)