Skip to content

Instantly share code, notes, and snippets.

@tanaka-takayoshi
Created November 1, 2022 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaka-takayoshi/7e634fc8b3732a028d40a047b87bb310 to your computer and use it in GitHub Desktop.
Save tanaka-takayoshi/7e634fc8b3732a028d40a047b87bb310 to your computer and use it in GitHub Desktop.
An example code to send metrics to New Relic
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
Console.WriteLine("Start sending metrics...");
var key = Environment.GetEnvironmentVariable("Api-Key");
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Api-Key", key);
var interval = TimeSpan.FromSeconds(60);
while (true)
{
var now = DateTimeOffset.UtcNow;
MetricsContent[] root;
var attributesA = new Dictionary<string, object>
{
{ "host", "HostA" }
};
var attributesB = new Dictionary<string, object>
{
{ "host", "HostB" }
};
if (now.Minute % 60 == 0)
{
root = new[]
{
new MetricsContent{
Metrics = new[]
{
new Metric
{
Name = "test.metrics1",
Type = "gauge",
Value = 10,
Timestamp = now.ToUnixTimeMilliseconds(),
Intervalms = (int)interval.TotalMilliseconds,
Attributes = attributesA
},
new Metric
{
Name = "test.metrics2",
Type = "gauge",
Value = 10,
Timestamp = now.ToUnixTimeMilliseconds(),
Intervalms = (int)interval.TotalMilliseconds,
Attributes = attributesB
}
}
}
};
}
else
{
root = new[]
{
new MetricsContent{
Metrics = new[]
{
new Metric
{
Name = "test.metrics1",
Type = "gauge",
Value = 0,
Timestamp = now.ToUnixTimeMilliseconds(),
Intervalms = (int)interval.TotalMilliseconds,
Attributes = attributesA
}
}
}
};
}
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
Console.WriteLine(JsonSerializer.Serialize(root, options));
var res = await client.PostAsync("https://metric-api.newrelic.com/metric/v1", JsonContent.Create(root, options:options));
Console.WriteLine(res.StatusCode);
Console.WriteLine(await res.Content.ReadAsStringAsync());
await Task.Delay(interval);
}
public class MetricsContent
{
public Metric[]? Metrics { get; set; }
}
public class Metric
{
public string? Name { get; set; }
public string? Type { get; set; }
public object? Value { get; set; }
public long Timestamp { get; set; }
[JsonPropertyName("interval.ms")]
public int Intervalms { get; set; }
public Dictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment