6

I am trying to dependency inject Serilog into all my projects in my WebAPI project in .Net Core 3.1.

In my startup.cs, I am setting up the serilog, but possibly incorrectly:

I have: using Serilog;

And then within: public void ConfigureServices(IServiceCollection services), I have:

services.AddSingleton(Log.Logger);

I also have:

            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json")
                        .AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true)
                        .Build();

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

This, in my controller class, I do the usual:

using Microsoft.Extensions.Logging;

private readonly ILogger _log;

public AuthorisationController(IConfiguration config, ISecurityService securityService, ILogger<AuthorisationController> log)
        {
            Configuration = config;
            _securityService = securityService;
            _log = log;
        }

Config and SecurityService are OK.

But in my first method, I try to log:

_log.LogInformation("Login attempt");

But nothing appears in my log.

Can anyone spot the mistake?

Not that it matters, but my appsettings has this:

    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "===> {Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "Loggly",
        "Args": {
          "customerToken": "MySuperSecretKey"
        }
      }
    ]
  }```

Craig
  • 18,074
  • 38
  • 147
  • 248
  • I'm not terribly savvy on Serilog, but can you check your `_log` field at runtime and check that the configuration got injected correctly. – Jonesopolis Oct 09 '20 at 12:57
  • I think you should reconsider your setup. I have worked with serilog a lot but never used the singleton (application lifetime) registration mode. Here's an article: https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/ – Stefan Oct 09 '20 at 12:59

1 Answers1

10

You haven't posted any logging configuration code yet, so I assume it's missing. There are several packages that integrate Serilog with the Logging extensions, some working with the generic host, some adding extensions specific to ASP.NET Core.

One option is to use the Serilog.AspNetCore. Once you create the logger you can use it with the host builder itself:

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

This will use the static logger both for the application and the host building process

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • This was indeed the issue. I thought that was only needed for console app. Foolish. Adding this, has solved the issue - partially. My application has API layer, Logic Layer and Data Access layer. API layer is logging, but lower layers - no logs. So I will seek the issue. Thanks. – Craig Oct 11 '20 at 22:34