Looking at the comment from @MarcGravell and this question about doing the same with Dapper, MiniProfiler.Integrations
is better way to implement logging for Dapper Extensions.
Above linked question is about Dapper. But Dapper Extensions uses Dapper internally. So, if logging is implemented for Dapper, same works for Dapper Extensions as well.
More details could be found on GitHub.
Sample code is as below:
var factory = new SqlServerDbConnectionFactory(connectionString);
CustomDbProfiler cp = new CustomDbProfiler();
using(var connection = DbConnectionFactoryHelper.New(factory, cp))
{
//DB Code
}
string log = cp.ProfilerContext.GetCommands();
You can use in-build CustomDbProfiler
using CustomDbProfiler.Current
if that suits your need. cp.ProfilerContext.GetCommands()
will return ALL the commands (success and failed) no matter how many times you call the method. I am not sure but, it might be maintaining concatenated string (StringBuilder
may be) internally. If this is the case, this may slow down the performance. But, in my case, logging is disabled by default. I only enable logging when I need to debug something. So this is not a problem for me.
This also may raise memory footprint issue if single connection is used over very large scope. To avoid this, make sure CustomDbProfiler
instance is disposed properly.
As mentioned in question, initially, I wanted to avoid this way (using external tool/library). But, MiniProfiler.Integrations
is NOT writing the log itself. I can simply get all the queries generated and provide those to my logger module to dump into the file. That is why, this looks more suitable to me now.
MiniProfiler.dll internally implements similar logic (in StackExchange.Profiling.Data.ProfiledDbConnection
and StackExchange.Profiling.Data.ProfiledDbCommand
classes) which is mentioned here and here. So, if I decide to (in future may be) bypass MiniProfiler, I can use this implementation myself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…