EnthuAz
EnthuAz

Reputation: 67

Track non-HTTP requests with Application Insights

As mentioned in this link, on .net core2.1 web.api application implemented the below code to track non-HTTP requests(i.e, redis calls) using Application Insights

 private ReviewModel<T> GetCachedData<T>(string id)
    {
        try
        {
            var obj = default(RedisValue);
            _retryPolicy.Execute(() =>
            {
                using (var getReviewsOperation = _telemetryClient.StartOperation<DependencyTelemetry>("RedisCall"))
                {
                    obj = _database.StringGet(id); // external call to redis server
                }
            });

            var review = string.IsNullOrEmpty(obj) || !obj.HasValue ?
                    default(ReviewModel<T>) : _serializer.Deserialize<ReviewModel<T>>(obj );
            return review;
        }
        catch (Exception ex)
            when (ex is RedisException)
        {
            //how to log the exception cases in dependency table of application insights log?
            _log.LogError($"Redis exception occurred : ", {ex.Message});
            return null;
        }
    }

The above code successfully log the redis call details on "dependency" table of application insights log. But how to log redis call details on "dependency" table of application insights log on exception scenarios with success property value as "false"?

Upvotes: 0

Views: 622

Answers (1)

Harshita Singh
Harshita Singh

Reputation: 4870

You can use TrackDependency for this. TrackDependency is used to track the response times and success rates of calls to an external piece of code. The results appear in the dependency charts in the portal. The code snippet below needs to be added wherever a dependency call is made:

var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
    success = dependency.Call();
}
catch(Exception ex) 
{
    success = false;
    telemetry.TrackException(ex);
    throw new Exception("Operation went wrong", ex);
}
finally
{
    timer.Stop();
    telemetry.TrackDependency("DependencyType", "myDependency", "myCall", startTime, timer.Elapsed, success);
}

Upvotes: 2

Related Questions