Search code examples
asp.net-mvc-3petapoco

Logging SqlCommand only in case of error w/ PetaPoco


I know I can log exceptions with PetaPoco thus:

public override void OnException(Exception x)
{
    _logger.LogError(x);
}

I also realize I can dump the command text + params:

public override void OnExecutingCommand(System.Data.IDbCommand cmd)
{
    _logger.LogInfo(cmd.CommandText);
    foreach (SqlParameter sqlParam in cmd.Parameters)
    {
        _logger.LogInfo(String.Format("Name: {0}; Value: {1}; SqlValue: {1}", sqlParam.ParameterName,
                                      sqlParam.Value, sqlParam.SqlValue));
    }
    base.OnExecutingCommand(cmd);
}

Naturally, I don't really want to log each command+params in a production environment.

What's the best approach to log the command + params only when an exception is thrown?

Thanks!


Solution

  • You can try this.

    public override void OnException(Exception x)
    {
        _logger.Log(LastCommand);
        _logger.LogError(x);
    }
    

    LastSql and LastArgs are also available.