Skip to content

Diagnostics: add cache key #50

@vtomskih

Description

@vtomskih

Description

I will be able to implement a metric observer in which I will write metrics for specific queries by key and see their counter and duration. In addition to metrics, this will allow you to expand the context of data in logs and traces.

My custom implementation:

internal class CustomMetricsMemcachedDiagnosticObserver
{
    private readonly ICustomMemcachedMetrics _metrics;

    public MetricsMemcachedDiagnosticListener(ICustomMemcachedMetrics metrics)
    {
        _metrics = metrics;
    }

    [DiagnosticName(MemcachedDiagnosticSource.CommandDurationDiagnosticName)]
    public void ObserveCommandDuration(string commandName, double duration, string cacheKey)
    {
        _metrics.ObserveCommandDurationSeconds(commandName, cacheKey, duration);
    }
    
    [DiagnosticName(MemcachedDiagnosticSource.CommandsTotalDiagnosticName)]
    public void ObserveCommandsTotal(string commandName, string isSuccessful, string cacheKey)
    {
        _metrics.IncrementExecutedCommand(commandName, cacheKey, isSuccessful);
    }
}
internal class NuGetMemcachedMetrics : ICustomMemcachedMetrics
{
    // ..fields
    // ..ctor

    public void ObserveCommandDurationSeconds(string commandName, string cacheKey, double durationSeconds)
    {
        var normalizedKey = GetNormalizedKey(cacheKey);

        _commandDurationSeconds.Record(
            durationSeconds,
            new KeyValuePair<string, object>(CommandNameLabel, commandName),
            new KeyValuePair<string, object>(CacheKeyLabel, normalizedKey)
        );
    }

    public void ObserveExecutedCommand(string commandName, string cacheKey, string isSuccessful)
    {
        var normalizedKey = GetNormalizedKey(cacheKey);

        _commandsTotal.Add(1,
            new KeyValuePair<string, object>[]
            {
                new(CommandNameLabel, commandName),
                new(CacheKeyLabel, cacheKey),
                new(IsSuccessfulLabel, isSuccessful)
            });
    }

    private static string GetNormalizedKey(string cacheKey)
    {
        if (string.IsNullOrEmpty(cacheKey))
            return "<no-cache-key>";

        return packageId.StartsWith("packages-", StringComparison.OrdinalIgnoreCase) ? "packages"
            : packageId.StartsWith("package-versions-", StringComparison.OrdinalIgnoreCase) ? "package-versions"
            : packageId.StartsWith("package-", StringComparison.OrdinalIgnoreCase) ? "package"
            : "mirror";
    }
}

What needs to be done

Add cacheKey to ObserveExecutedCommand and ObserveCommandDurationSeconds.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions