Is there any way to trace\log the sql using Dapper?

Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.

In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:

  • (primarily) security: since dapper doesn't have a concept of a context, it would be really really easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
  • (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be null in most cases) would have much impact

Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: Debug.WriteLine etc.


Try Dapper.Logging.

You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.

In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.

From the documentation:

The tool consists of simple decorators for the DbConnection and DbCommand which track the execution time and write messages to the ILogger<T>. The ILogger<T> can be handled by any logging framework (e.g. Serilog). The result is similar to the default EF Core logging behavior.

The lib declares a helper method for registering the IDbConnectionFactory in the IoC container. The connection factory is SQL Provider agnostic. That's why you have to specify the real factory method:

services.AddDbConnectionFactory(prv => new SqlConnection(conStr));

After registration, the IDbConnectionFactory can be injected into classes that need a SQL connection.

private readonly IDbConnectionFactory _connectionFactory;
public GetProductsHandler(IDbConnectionFactory connectionFactory)
{
    _connectionFactory = connectionFactory;
}

The IDbConnectionFactory.CreateConnection will return a decorated version that logs the activity.

using (DbConnection db = _connectionFactory.CreateConnection())
{
    //...
}

You should consider using SQL profiler located in the menu of SQL Management Studio → Extras → SQL Server Profiler (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).

Then, start a new session.

You'll get something like this for example (you see all parameters and the complete SQL string):

exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0) 
                    AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'

I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget MiniProfiler.Integrations I would like to share.

Update V2: it supports to work with other database servers, for MySQL it requires to have MiniProfiler.Integrations.MySql

Below are steps to work with SQL Server:

1.Instantiate the connection

var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
 // your code
}

2.After all works done, write all commands to a file if you want

File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());

Tags:

Dapper