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 17 commits
Commits
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>
88 changes: 88 additions & 0 deletions examples/GroceryExample/GroceryStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// <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 CounterMetric<long> itemCounter;

private CounterMetric<double> cashCounter;

private BoundCounterMetric<double> boundCashCounter;

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

// Setup Metrics

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

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

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

var labels = new MyLabelSet(
new KeyValuePair<string, string>("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 = new MyLabelSet(
new KeyValuePair<string, string>("Store", "Portland"),
new KeyValuePair<string, string>("Customer", customer),
new KeyValuePair<string, string>("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 = new MyLabelSet(
new KeyValuePair<string, string>("Store", "Portland"),
new KeyValuePair<string, string>("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;
});
}
}
}
39 changes: 39 additions & 0 deletions examples/GroceryExample/Misc/MyMetricProcessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// <copyright file="MyMetricProcessor.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 System.Threading;
using OpenTelemetry.Metrics.Export;

#pragma warning disable CS0618

namespace GroceryExample
{
public class MyMetricProcessor : MetricProcessor
{
private List<Metric> items = new List<Metric>();

public override void FinishCollectionCycle(out IEnumerable<Metric> metrics)
{
metrics = Interlocked.Exchange(ref this.items, new List<Metric>());
}

public override void Process(Metric metric)
{
this.items.Add(metric);
}
}
}
39 changes: 39 additions & 0 deletions examples/GroceryExample/MyLabelSet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// <copyright file="MyLabelSet.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;

#pragma warning disable CS0618

namespace GroceryExample
{
public class MyLabelSet : LabelSet
victlu marked this conversation as resolved.
Show resolved Hide resolved
{
public MyLabelSet(params KeyValuePair<string, string>[] labels)
{
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
foreach (var kv in labels)
{
list.Add(kv);
}

this.Labels = list;
}

public override IEnumerable<KeyValuePair<string, string>> Labels { get; set; } = System.Linq.Enumerable.Empty<KeyValuePair<string, string>>();
}
}
Loading