Read InMemory logs from serilog .Net Core Web API with Dependency Injection

Viewed 342

Goal is to read all the log added to serilog in this session and pass back to client, even from internal assembly's log (Internal assembly too have serilog for capture error and required information)

Tried to read using "Serilog.Sinks.InMemory" but it fails for dependency injected project. But same working when we create the logger in same class

Please refer below code and help me to find what could be the error.

Basic Details, Application : .Net Core Web Api Version : Core 3.1

Steps I followed,

  1. Installed Package 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. Added InMemory Sink in LoggerConfiguration in Program.cs

     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");
                }
        }
    }

Suggestion welcome to read Serilog logs (Information/Error/Warning) for current session

Thanks in advance

0 Answers
Related