Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dapper

Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.

like image 681
Mladen Mihajlovic Avatar asked Aug 30 '13 09:08

Mladen Mihajlovic


People also ask

How do I log in Dapper query?

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.

Is Dapper safe from SQL injection?

How does Dapper help protect against SQL injections? It makes it really, really easy to do fully parameterized data access, without ever needing to either concatenate input.


2 Answers

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()); 
like image 54
hazjack Avatar answered Sep 29 '22 17:09

hazjack


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.

like image 28
Marc Gravell Avatar answered Sep 29 '22 17:09

Marc Gravell