locked
Logger to log from appsettings.json RRS feed

  • Question

  • User2097725413 posted

    Hi,

    In my application, I am writing all errors/ information in a Log file.

    Now I want to implement the logger to log only from the configuration of appsettings.json.

    In appsettings.json, I have configured as below,

    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Warning"
    }
    },

    "Serilog": {
    "MinimumLevel": {
    "Default": "Debug",
    "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
    }
    }
    },

    In Startup.cs

    ConfigureServices -

    services.AddLogging(builder =>
    {
    builder.AddFilter("Microsoft", LogLevel.Warning)
    .AddFilter("System", LogLevel.Warning)
    .AddFilter("NToastNotify", LogLevel.Warning)
    .AddConsole();
    });

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    loggerFactory.AddFile("Logs/AppLogs-{Date}.txt");
    loggerFactory.AddConsole(LogLevel.Warning);

    }

    However I want to log only application errors which is configured in appsettings.json.

    for e.g in HomeController 

    // WRITE LOG Information
    _logger.LogInformation((int)LoggingEvents.GENERATE_ITEMS, "Get User list.");
    _logger.Log(LogLevel.Information, "Get User list.");

    // WRITE EXCEPTION LOG
    Exception ex = new Exception();
    _logger.LogError(default(EventId), ex, "Test Exception");

    The above line logs,

    2019-06-03T16:03:45.8994622+01:00 0HLN86IMD3IMU:00000001 [INF] Get User list. (33f5e0b3)
    2019-06-03T16:03:45.9050192+01:00 0HLN86IMD3IMU:00000001 [ERR] Test Exception (96082a69)

    As I selected LogLevel to Warning, till its logging [INF], i did not want to log the information of [inf].

    How to write/configure the functionality which works from appsettings.json to log "Errors" only .

    Thanks.

    Monday, June 3, 2019 3:25 PM

All replies

  • User-854763662 posted

    Hi Uday Mahajan ,

    ASP.NET Core defines the following log levels, ordered here from lowest to highest severity. Refer to here

    Trace = 0 --> Debug = 1 --> Information = 2 --> Warning = 3 --> Error = 4 --> Critical = 5

    If you want to log "Errors" only to log file , you could try to change the MinimumLevel of Serilog like below :

    "Serilog": {
        "MinimumLevel": {
          "Default": "Error", // get log information of "Error" and above
          "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
          }
        },
    }

    If you set the MinimumLevel to "Warning" , you will get the log information of "Warning"  , " Error" and above .

    Best Regards ,

    Sherry

    Tuesday, June 4, 2019 6:53 AM