Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Grocery Example for Metrics API #1831

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .markdownlint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"default": true,
"line-length": {
"tables": false
}
}

30 changes: 30 additions & 0 deletions examples/GroceryExample/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
// Use IntelliSense to learn about possible attributes.
victlu marked this conversation as resolved.
Show resolved Hide resolved
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"OS-COMMENT1": "Use IntelliSense to find out which attributes exist for C# debugging",
"OS-COMMENT2": "Use hover for the description of the existing attributes",
"OS-COMMENT3": "For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md",
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"OS-COMMENT4": "If you have changed target frameworks, make sure to update the program path.",
"program": "${workspaceFolder}/bin/Debug/net5.0/GroceryExample.dll",
"args": [],
"cwd": "${workspaceFolder}",
"OS-COMMENT5": "For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console",
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
42 changes: 42 additions & 0 deletions examples/GroceryExample/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/GroceryExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/GroceryExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/GroceryExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
17 changes: 17 additions & 0 deletions examples/GroceryExample/GroceryExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Api\OpenTelemetry.Api.csproj">
<Project>{99f8a331-05e9-45a5-89ba-4c54e825e5b2}</Project>
<Name>OpenTelemetry.Api</Name>
</ProjectReference>
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry\OpenTelemetry.csproj">
<Project>{ae3e3df5-4083-4c6e-a840-8271b0acde7e}</Project>
<Name>OpenTelemetry</Name>
</ProjectReference>
</ItemGroup>
</Project>
96 changes: 96 additions & 0 deletions examples/GroceryExample/GroceryStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// <copyright file="GroceryStore.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Collections.Generic;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

#pragma warning disable CS0618

namespace GroceryExample
{
public class GroceryStore
{
private static Dictionary<string, double> priceList = new Dictionary<string, double>()
{
{ "potato", 1.10 },
{ "tomato", 3.00 },
};

private string storeName;

private Meter meter;

private CounterMetric<long> itemCounter;

private CounterMetric<double> cashCounter;

private BoundCounterMetric<double> boundCashCounter;

public GroceryStore(string storeName)
{
this.storeName = storeName;

// Setup Metrics

this.meter = MeterProvider.Default.GetMeter("GroceryStore", "1.0.0");

this.itemCounter = this.meter.CreateInt64Counter("item_counter");

this.cashCounter = this.meter.CreateDoubleCounter("cash_counter");

var labels = this.meter.GetLabelSet(new List<KeyValuePair<string, string>>()
{
KeyValuePair.Create("Store", "Portland"),
});

this.boundCashCounter = this.cashCounter.Bind(labels);
}

public void ProcessOrder(string customer, params (string name, int qty)[] items)
{
double totalPrice = 0;

foreach (var item in items)
{
totalPrice += item.qty * priceList[item.name];

// Record Metric

var labels = this.meter.GetLabelSet(new List<KeyValuePair<string, string>>()
{
KeyValuePair.Create("Store", "Portland"),
KeyValuePair.Create("Customer", customer),
KeyValuePair.Create("Item", item.name),
});

this.itemCounter.Add(default(SpanContext), item.qty, labels);
victlu marked this conversation as resolved.
Show resolved Hide resolved
}

// Record Metric

var labels2 = this.meter.GetLabelSet(new List<KeyValuePair<string, string>>()
{
KeyValuePair.Create("Store", "Portland"),
KeyValuePair.Create("Customer", customer),
});

this.cashCounter.Add(default(SpanContext), totalPrice, labels2);

this.boundCashCounter.Add(default(SpanContext), totalPrice);
victlu marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
77 changes: 77 additions & 0 deletions examples/GroceryExample/Misc/MyMetricExporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// <copyright file="MyMetricExporter.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Metrics.Export;

#pragma warning disable CS0618

namespace GroceryExample
{
public class MyMetricExporter : MetricExporter
{
public override Task<ExportResult> ExportAsync(IEnumerable<Metric> metrics, CancellationToken cancellationToken)
{
return Task.Run<ExportResult>(() =>
{
StringBuilder sb = new StringBuilder();

sb.AppendLine("Exporting...");
foreach (var m in metrics)
{
sb.AppendLine($"[{m.MetricNamespace}:{m.MetricName}]");

foreach (var data in m.Data)
{
sb.Append(" ");

string val = "-";
if (data is DoubleSumData doublesum)
{
val = $"Sum={doublesum.Sum}";
}
else if (data is Int64SumData int64sum)
{
val = $"Sum={int64sum.Sum}";
}
else
{
val = data.ToString();
}

sb.Append($"Data: {val}, ");

sb.Append("Labels: ");
foreach (var l in data.Labels)
{
sb.Append($"{l.Key}={l.Value}, ");
}

sb.AppendLine();
}
}

Console.WriteLine(sb.ToString());

return ExportResult.Success;
});
}
}
}
60 changes: 60 additions & 0 deletions examples/GroceryExample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Threading.Tasks;
using OpenTelemetry.Metrics;
using OpenTelemetry.Metrics.Export;

#pragma warning disable CS0618

namespace GroceryExample
{
public class Program
{
public static void Main(string[] args)
{
// Create Metric Pipeline

var sdk = OpenTelemetry.Sdk.CreateMeterProviderBuilder()
.SetPushInterval(TimeSpan.FromMilliseconds(1000))

// Need to have a processor to move Metrics through pipeline
.SetProcessor(new UngroupedBatcher())

.SetExporter(new MyMetricExporter())

.Build()
;

// Need to set for the Default provider
MeterProvider.SetDefault(sdk);

var store = new GroceryStore("Portland");

store.ProcessOrder("customerA", ("potato", 2), ("tomato", 3));
store.ProcessOrder("customerB", ("tomato", 10));
store.ProcessOrder("customerC", ("potato", 2));
store.ProcessOrder("customerA", ("tomato", 1));

// Wait for stuff to run
Task.Delay(5000).Wait();

// Shutdown Metric Pipeline
// sdk.Shutdown();
}
}
}
29 changes: 29 additions & 0 deletions examples/GroceryExample/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Overview

The goal of this Grocery example is to try and instrument the code. From this
excersize we hope to discover and learn additional topics for discussions.

We are focus only on the API side at the moment. It is known that SDK
implementation will likely affect how the API is designed, but we will make our
best judgement to tolerate the situation at this time.

## Topics for discussions

- Need some kind of concrete LabelSet() in API. Access to LabelSetSdk() is
unavailable from API side.

- It is inconvenient to have to pass a default(SpanContext) when we don't care
about spans. Need additional prototypes to make SpanContext optional.
victlu marked this conversation as resolved.
Show resolved Hide resolved

- We create instrument with CreateInt64Counter() but it returns a generic
Counter&lt;long&gt;. Seems like it should return a Int64Counter instead.

- It's not allowed to new MeterProvider(). Thus, the only way to access is via
the Default property. We can probably simplify MeterProvider.Default.GetMeter()
to simply MeterProvider.GetMeter().

- Bound counters does not allow adding more labels. Ideally, we would bind
victlu marked this conversation as resolved.
Show resolved Hide resolved
Store, but still allow passing in additional lables (i.e. Customer) when
recording measurements.

- Need shutdown() for SDK
Loading