Chris
Chris

Reputation: 27394

Log EF query time to database

I want to log EF query (or transaction) times back to the database so that I can monitor performance in a live system. Note I know that more than one query can happen within my UOW. That is fine, I just want to be able to tell what areas of the system are slowing down etc.

What is the best way for me to do this? My initial thought was to do this in UnitOfWork.Dispose() so that every query would automatically be logged once completed. But this smells a bit to me because I'd have to call Save() to persist the information, but what if the caller didn't want to save?

Is there another, better way I can automatically log the query time to the database?

protected virtual void Dispose(bool disposing)
{
    if (this.logQueryToDatabase)
    {
        var timeTaken = DateTime.UtcNow - this.start;
        LogPerformance(this.callingFnName, timeTaken.TotalMilliseconds);
    }

    this.ctx.Dispose();
}

Upvotes: 0

Views: 91

Answers (1)

Ako
Ako

Reputation: 1221

If you know which actions to measure you can create a simple class to handle this. All you need is to wrap around the action.

The profiler class.

public class Profiler:IDisposable
{
    private readonly string _msg;
    private Stopwatch _sw;

    public Profiler(string msg)
    {
        _msg = msg;
        _sw = Stopwatch.StartNew();
    }

    public void Dispose()
    {
        _sw.Stop();
        LogPerformance(_msg, _sw.ElapsedMilliseconds);
    }
}

The usage:

using (new Profiler("Saving products"))
{   
    db.SaveChanges();
}

Upvotes: 1

Related Questions