1. Install Required Packages
You need Newtonsoft.Json for logging structured data and System.Net.Http for API requests. Install via NuGet:
dotnet add package Newtonsoft.Json
2. Write the C# Monitoring Script
This script sends API requests, checks responses, logs performance, and reports issues.
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main()
{
string apiUrl = "https://your-api-url.com/health"; // Replace with your API endpoint
using HttpClient client = new HttpClient();
try
{
Stopwatch stopwatch = Stopwatch.StartNew();
HttpResponseMessage response = await client.GetAsync(apiUrl);
stopwatch.Stop();
var logEntry = new
{
Timestamp = DateTime.UtcNow,
ApiUrl = apiUrl,
StatusCode = (int)response.StatusCode,
ResponseTimeMs = stopwatch.ElapsedMilliseconds,
Success = response.IsSuccessStatusCode
};
Console.WriteLine(JsonConvert.SerializeObject(logEntry, Formatting.Indented));
if (!response.IsSuccessStatusCode)
{
ReportToNewRelic(logEntry);
}
}
catch (Exception ex)
{
var errorLog = new
{
Timestamp = DateTime.UtcNow,
ApiUrl = apiUrl,
Error = ex.Message,
Success = false
};
Console.WriteLine(JsonConvert.SerializeObject(errorLog, Formatting.Indented));
ReportToNewRelic(errorLog);
}
}
static void ReportToNewRelic(object logData)
{
// Placeholder for sending logs to New Relic
Console.WriteLine("Reporting issue to New Relic...");
// You can integrate with New Relic's API or log monitoring system
}
}
3. How It Works
✅ Sends API requests to the health check endpoint.
✅ Measures response time in milliseconds.
✅ Logs API status, response code, and errors.
✅ Reports failures to New Relic (custom integration needed).
4. Automating API Monitoring
To run this script automatically:
- Use Windows Task Scheduler (Windows) or a Cron Job (Linux/Mac)
- Run every 5 minutes to check API health
- Extend logging to New Relic by sending data to New Relic Logs API
5. Sending Data to New Relic Logs API
To log issues in New Relic, send API data using HttpClient:
static async void ReportToNewRelic(object logData)
{
string newRelicApiKey = "YOUR_NEW_RELIC_LICENSE_KEY";
string newRelicLogEndpoint = "https://log-api.newrelic.com/log/v1";
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Api-Key", newRelicApiKey);
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
string jsonPayload = JsonConvert.SerializeObject(new { logs = new[] { logData } });
try
{
HttpResponseMessage response = await client.PostAsync(newRelicLogEndpoint, new StringContent(jsonPayload));
Console.WriteLine($"New Relic Log Response: {response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send logs to New Relic: {ex.Message}");
}
}
