Skip to content
This repository was archived by the owner on Apr 18, 2022. It is now read-only.
This repository was archived by the owner on Apr 18, 2022. It is now read-only.

Sometimes logs are note written to the CosmosDb #86

@mahdighorbanpour

Description

@mahdighorbanpour

Hi,
I'm using CosmosDb sink in a .net core 3.1 web API project, and it works with normal logging things, but whenever I use a BeginScope then sometimes logs are written in the CosmosDb and most of the times NOT.
##Program.cs

public static void Main(string[] args)
        {

            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            using (var logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger())
            {
                Log.Logger = logger;
                try
                {
                    Log.Information("Starting up");
                    CreateHostBuilder(args).Build().Run();
                }
                catch (Exception ex)
                {
                    Log.Fatal(ex, "Application start-up failed");
                }
                finally
                {
                    Log.CloseAndFlush();
                }
            }
        }

       public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

##appSettings.json

{
"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "{Timestamp:HH:mm:ss} [{Level:u3}] [{SourceContext}] {Scope} {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "AzureTableStorageWithProperties",
        "Args": {
          "storageTableName": "AppLogs",
          "connectionString": "xxxx",
          "propertyColumns": [ "Scope", "RequestId" ]
        }
      },
      {
        "Name": "AzureDocumentDB",
        "Args": {
          "endpointUrl": "https://xxxx.documents.azure.com",
          "authorizationKey": "xxxx=="
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "%TEMP%/Logs/AppLogs.txt",
          "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}/{ThreadName}) {Message}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "App"
    }
  }
}

##Controller

public class LogsController : ControllerBase
    {
        private readonly ILogger<LogsController> _logger;
        public LogsController(            
            ILogger<LogsController> logger
            )
        {            
            _logger = logger;
        }

        [HttpPost("installation")]
        [AllowAnonymous]
        public async Task<IActionResult> ReportInstallerLogs(InstallationLogsDto input)
        {
            try
            {
                if (input == null)
                {
                    throw new ArgumentNullException(nameof(input));
                }
                
                // import the logs
               using (_logger.BeginScope($"IPIN {input.Ipin}"))
                {
                    if (input.CompletedSuccessfully)
                    {
                        _logger.LogInformation("Install succeeded!");
                    }
                    else
                    {
                        _logger.LogError("InstallationFailed");
                    }
                }                
                return Ok();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return StatusCode(400, ex.Message);
            }
        }
    }

I have already read this issue, but I'm not sure how can I use it within a controller and DI.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions