简体   繁体   中英

Serilog not logging information logs

In my .NET Core 2.1 project I have installed Serilog , but for some reason it will not log information events. It logs error events, though.

In my appSettings I have:

    "Serilog": {
        "MinimumLevel": {
          "Default": "Information",
          "Override": {
            "Microsoft": "Fatal",
            "System": "Fatal"
          }
        },
        "WriteTo": [
          {
            "Name": "File",
            "Args": {
              "restrictedToMinimumLevel": "Information",
              "path": "D:\\Web\\098_VDSNet4\\Logs\\API.AdminPortal\\.txt",
              "rollingInterval": "Day"
            }
          }
        ]
      }

and in my Startup.cs I have:

                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .ReadFrom.Configuration(Configuration)
                    .CreateLogger();

                services.AddLogging(logging =>
                    logging.AddSerilog(dispose: true)
                );

In the code I have:

            public IActionResult Post(Address address)
            {
                string functionName = "AddressController:Post";

                try
                {
                    logger.LogInformation($"{functionName}");

                    // TOOD Additional Address validation
                    addressRepository.Add(address);
                    addressRepository.Save();

                    return Ok(address);
                }
                catch(Exception ex)
                {
                    logger.LogError(ex, $"{functionName}: There was an error creating the address");
                    return BadRequest();
                }

            }

logger.LogInformation (and I have tried logger.LogDebug as well, that doesn't work either) does not output anything. But logger.LogError does log the correct error.

I have tried changing the default level to Verbose to see if that would kick it into life, but I can't seem to get anything below Error to be output to the log file.

You have to inject the ILogger<HomeController> interface into your HomeController constructor.

    private readonly Microsoft.Extensions.Logging.ILogger _log;

    public HomeController(ILogger<HomeController> logger)
    {
        _log = logger;
    }

You have to tell asp.net core from where to read the configuration (add this in Program.cs ):

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

In the Program.cs add UseSerilog :

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog();

Results:

错误和信息的结果

Inject your log into your controller through the constructor in order to use it.

using Serilog;

public class MyController : Controller
{
    private readonly ILogger _log;

    public MyController(ILogger log)
    {            
        _log = log;
    }

    public IActionResult Post(Address address)
    {
        //Make sure you are using the variable you set up in this controller
        _log.Information**("Hello World!");
    }
}

Make sure you are using the variable you create in your controller that is assigned in the constructor. Do not use Logger.LogInformation. Use _log.Information. The logger that you are injecting is the one that you are configuring. Logger.LogInformation is using the Microsoft logger not the serlilog that you set up. Serilog would be .Information not .LogInformation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM