To get text written to the SQL Server XEvent profile, I have written the following method:
protected async Task LogToProfiler(string message)
{
await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
{
await dbContext.Database.ExecuteSqlAsync($"-- {message}");
}
}
It works great, writing out the messages where I want to the profiler event list. The problem is, what I need is:
#if DEBUG
protected async Task LogToProfiler(string message)
{
await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
{
await dbContext.Database.ExecuteSqlAsync($"-- {message}");
}
}
#else
protected void LogToProfiler(string message) {}
#end
So that in release mode there is no set up and tear down of a Task
. Is there a way to do this?
Also, I do call it as:
if (profilingOn)
await LogToProfiler("entering method");
Is this sufficient to avoid the setup/teardown if profilingOn == false? I believe it is. It's safer to use #if DEBUG
but I can force profilingOn
to false if it's built for RELEASE
.
My fundamental concern is developers make mistakes and so it might end up being called even if profilingOn is false and we're running in RELEASE
mode. So I want to be as safe as possible.