question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Serilog and WebApplicationFactory

See original GitHub issue

I have a .NET Core 2.1 project. I’m running tests using the new WebApplicationFactory. This uses information in the program.cs to bootstrap things.

When running tests, I wan’t to mock the ILogger infrastructure, not use the Serilog implementation. From what I can tell, it’s not trivial to remove the Serilog implementation from DI.

Serilog is set up in program.cs like this:

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog((context, configureLogger) =>
                {
                       // configuration omitted. 
                });

This is a cut down version of my Testing contex

 public class TestingContext : WebApplicationFactory<Startup>
    {
        /// <summary>
        /// Mocked ILogger
        /// </summary>
        public Mock<ILogger> Logger { get; } = new Mock<ILogger>();

        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            var loggerProvider = new Mock<ILoggerProvider>();
            loggerProvider.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(Logger.Object);

            builder
                .UseDefaultServiceProvider(p => p.ValidateScopes = true)
                .ConfigureLogging(l =>
                {
                    // this is the only way I have found to remove Serilog
                    var serilog = (from s in l.Services
                        where s.ImplementationFactory != null &&
                              s.ImplementationFactory.Target.GetType().Assembly.FullName.Contains("Serilog.AspNetCore")
                        select s).FirstOrDefault();

                    if (serilog != null)
                    {
                        l.Services.Remove(serilog);
                    }

                    // this does not clear Serilog, it removes all ILoggerProvider
                    // Serilog is registered as an ILoggerFactory
                    l.ClearProviders(); 
                    l.AddProvider(loggerProvider.Object);
                });
        }
    }

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kimbellcommented, Jul 25, 2018

One of the first statements from that repos read me file is:

ASP.NET Core 2.0+ Instructions ASP.NET Core 2.0 applications should prefer Serilog.AspNetCore and UseSerilog() instead.

The AspNetCore package replaces the default LoggerFactory registered by Microsoft. Looking at the SerilogLoggerFactory, it’s using a SerilogLoggerProvider that is of type ILoggerProvider.

Since one has gone through the effort of creating a new LoggerFactory, I’m assuming there is a reason for this. I’m curious as to why? What does it bring to the table that isn’t possible by just adding Serilog as another provider?

1reaction
nblumhardtcommented, Jul 24, 2018

@kimbell ClearProviders() removes providers from the default logger factory; since Serilog replaces the default logger factory, there’s no way ClearProviders() can have this effect. Thanks for the feedback, though - good to have this here for others who need the same info 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to silence Serilog in integration tests with the new ...
Update 2022-12-19: I just found a more clean way that works even without Serilog: [CollectionDefinition("WebApplicationFactory")] public ...
Read more >
Integration Testing ASP.NET Core WebApi
Build(); // I used serilog for logging. ... We require a web application factory to host an instance of the web application.
Read more >
Serilog.Sinks.XUnit.Injectable 1.0.26
The injectable, xUnit test output sink for Serilog. ... Integration tests (i.e. WebApplicationFactory ); Unit tests that utilize Dependency Injection in a ...
Read more >
Testing in .NET 6 with WebApplicationFactory (including ...
This article aims to discuss the benefits of integration testing in web applications and shows how the WebApplicationFactory class helps with this.
Read more >
Using Serilog with Microsoft ILogger in .NET 7 | by Lee Dale
Serilog is a popular logging library that can be used with ILogger to write logs to various ... NET with WebApplicationFactory (including Minimal...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found