title: Entity Framework Core: Log queries for a single db context instance
body: <p>Using EF Core (or any ORM for that matter) I want to keep track of the number of queries the ORM makes to the database during some operation in my software.</p>
  
  <p>I've used SQLAlchemy under Python earlier, and on that stack this is faily easy to set up. I typically have unit tests that assert on the number of queries made for a scenario, against an in-memory SQLite database.</p>
  
  <p>Now I want to do the same thing using EF Core, and have looked at the <a href="https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging" rel="noreferrer">Logging documentation</a>.</p>
  
  <p>In my test setup code I do as the documentation says:</p>
  
  <pre><code>using (var db = new BloggingContext())
  {
      var serviceProvider = db.GetInfrastructure&lt;IServiceProvider&gt;();
      var loggerFactory = serviceProvider.GetService&lt;ILoggerFactory&gt;();
      loggerFactory.AddProvider(new MyLoggerProvider());
  }
  </code></pre>
  
  <p>But I run into problems that I suspect are the results of the following (also from the docs):</p>
  
  <blockquote>
    <p>You only need to register the logger with a single context instance.
    Once you have registered it, it will be used for all other instances
    of the context in the same AppDomain.</p>
  </blockquote>
  
  <p>The problems I see in my tests indicates that my logger implementation is shared across multiple contexts (this is in accordance with the docs as I read them). And since a) my test runner runs tests in parallell and b) my entire test suite creates hundreds of db contexts - it does not work very well.</p>
  
  <p>Question/issues:</p>
  
  <ul>
  <li>Is what I want possible?</li>
  <li>I.e. can I register a logger with a db context that is only used for that db context instance?</li>
  <li>Are there other ways to accomplish what I am trying to do?</li>
  </ul>