In my case it's a web API project in Visual Studio. When I'm testing, the API is called multiple times concurrently.
I'm using the following to log the Raw SQL being sent to the SQL Server:
context.Database.Log = Console.WriteLine;
When SQL is logged, it's getting mixed up with queries on other threads. More specifically, it's most-often the parameters which get mixed up. This makes it next to impossible to correlate the right parameters with the right query. Sometimes the same API is called twice concurrently.
I am using async calls, but that wouldn't be causing the issue. It will be the fact there are multiple concurrent web requests on different completion threads.
I need accurate reliable logging so I can look back in the output window and review the SQL.
You need to buffer all log messages per-context, then write out that buffer upon disposal of your db context.
You need to be able to hook into your db context's dispose event
Then you need this class to manage the buffering per-context
It should work without saving a strong reference to the LogGroup object. But I haven't tested that yet. Also, you could include this kind of code directly on the context, so you definitely won't need to save a LogGroup reference object. But that wouldn't be as portable.
To use it in a controller action funtion:
Note, that I pass the controller reference, so the log can include some extra context information - the request URI.
Interpreting your log
Now that the log works, you'll find the commented parameters in the log output are a pain to work with. You would normally have to manually change them to proper SQL parameters, but even then it's difficult to run sub-sections of a larger SQL query with parameters.
I know there are one or two other ways to get EF to output the log. Those methods do provide better control over how parameters are output, but given the answer is about making Database.Log work I'll include this tool in WinForms, so it can rewrite your clipboard with a functional query.