From a4ab1ca068c006725d0a8093c693e63170d8f63d Mon Sep 17 00:00:00 2001 From: Pavel Reshetnikov Date: Tue, 26 Nov 2024 14:52:48 +0500 Subject: [PATCH] Complete task --- Dockerfile | 15 +++++++ Metrics.cs | 23 +++++++++++ Pages/Index.cshtml.cs | 13 ++++++- Program.cs | 29 ++++++++++++++ README.md | 3 +- compose.yaml | 24 ++++++++++++ logs | 91 +++++++++++++++++++++++++++++++++++++++++++ prometheus.yml | 6 +++ telemetry.csproj | 10 +++++ 9 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 Dockerfile create mode 100644 Metrics.cs create mode 100644 compose.yaml create mode 100644 logs create mode 100644 prometheus.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f41453e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM mcr.microsoft.com/dotnet/sdk:8.0@sha256:35792ea4ad1db051981f62b313f1be3b46b1f45cadbaa3c288cd0d3056eefb83 AS build-env +WORKDIR /App + +# Copy everything +COPY . ./ +# Restore as distinct layers +RUN dotnet restore WeatherApp.sln +# Build and publish a release +RUN dotnet publish -c Release -o out WeatherApp.sln + +# Build runtime image +FROM mcr.microsoft.com/dotnet/aspnet:8.0@sha256:6c4df091e4e531bb93bdbfe7e7f0998e7ced344f54426b7e874116a3dc3233ff +WORKDIR /App +COPY --from=build-env /App/out . +ENTRYPOINT ["./telemetry"] diff --git a/Metrics.cs b/Metrics.cs new file mode 100644 index 0000000..fc066f5 --- /dev/null +++ b/Metrics.cs @@ -0,0 +1,23 @@ +using System.Diagnostics.Metrics; + +namespace telemetry; + +public class Metrics +{ + private readonly Counter indexRequestsCount; + private readonly Histogram indexRequestsTime; + public const string Meter = nameof(Metrics); + + public Metrics(IMeterFactory meterFactory) + { + var meter = meterFactory.Create(Meter); + indexRequestsCount = meter.CreateCounter("requests.index.count", "pcs", "Количество запросов"); + indexRequestsTime = meter.CreateHistogram("requests.index.time", "ms", "Время запроса к index"); + } + + public void RequestToIndex(TimeSpan elapsed) + { + indexRequestsCount.Add(1); + indexRequestsTime.Record(elapsed.TotalMilliseconds); + } +} diff --git a/Pages/Index.cshtml.cs b/Pages/Index.cshtml.cs index 34a599f..2f6c11d 100644 --- a/Pages/Index.cshtml.cs +++ b/Pages/Index.cshtml.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -6,14 +7,22 @@ namespace telemetry.Pages; public class IndexModel : PageModel { private readonly ILogger _logger; + private readonly Metrics _metrics; - public IndexModel(ILogger logger) + public IndexModel(ILogger logger, Metrics metrics) { _logger = logger; + _metrics = metrics; } public void OnGet() { - + var sw = Stopwatch.StartNew(); + for (var i = 0; i < new Random().Next(0, 100); i++) + { + Console.Write("1"); + } + sw.Stop(); + _metrics.RequestToIndex(sw.Elapsed); } } diff --git a/Program.cs b/Program.cs index bc275e4..b04d02d 100644 --- a/Program.cs +++ b/Program.cs @@ -1,8 +1,35 @@ +using OpenTelemetry.Logs; +using OpenTelemetry.Metrics; +using OpenTelemetry.Resources; +using OpenTelemetry.Trace; +using telemetry; + var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); +builder.Logging.AddOpenTelemetry(options => +{ + options + .SetResourceBuilder( + ResourceBuilder.CreateDefault() + .AddService("TelemetryExample")) + .AddConsoleExporter(); +}); +builder.Services.AddOpenTelemetry() + .ConfigureResource(resource => resource.AddService("TelemetryExample")) + .WithTracing(tracing => tracing + .AddAspNetCoreInstrumentation() + .AddConsoleExporter()) + .WithMetrics(metrics => metrics + .AddPrometheusExporter() + .AddAspNetCoreInstrumentation() + .AddConsoleExporter() + .AddMeter(Metrics.Meter)); + +builder.Services.AddSingleton(); + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -22,4 +49,6 @@ app.MapRazorPages(); +app.UseOpenTelemetryPrometheusScrapingEndpoint(); + app.Run(); diff --git a/README.md b/README.md index 052e3ca..ce6b699 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ services: Создай рядом с `compose.yaml` файл `prometheus.yml` с содержимым ```yaml +scrape_configs: - job_name: "prometheus" # Override the global default and scrape targets from this job every 5 seconds. scrape_interval: 5s @@ -215,4 +216,4 @@ for (var i = 0; i < new Random().Next(0, 100); i++) sw.Stop(); _metrics.RequestToIndex(sw.Elapsed); ``` -Запусти приложение и посмотри в endpoint'е `/metrics` свои метрики. \ No newline at end of file +Запусти приложение и посмотри в endpoint'е `/metrics` свои метрики. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..9fe4499 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,24 @@ +services: + prometheus: + image: "prom/prometheus" + ports: + - "9090:9090" + volumes: + - "./prometheus.yml:/etc/prometheus/prometheus.yml" + extra_hosts: + - "host.docker.internal:host-gateway" + + grafana: + image: "grafana/grafana-oss" + ports: + - "3000:3000" + extra_hosts: + - "host.docker.internal:host-gateway" + + server: + build: . + ports: + - "5149:5149" + - "9000:9000" + extra_hosts: + - "host.docker.internal:host-gateway" diff --git a/logs b/logs new file mode 100644 index 0000000..dc3bbd7 --- /dev/null +++ b/logs @@ -0,0 +1,91 @@ +Building... +info: Microsoft.Hosting.Lifetime[14] + Now listening on: http://localhost:5149 +LogRecord.Timestamp: 2024-11-19T10:49:38.2320330Z +LogRecord.CategoryName: Microsoft.Hosting.Lifetime +LogRecord.Severity: Info +LogRecord.SeverityText: Information +LogRecord.Body: Now listening on: {address} +LogRecord.Attributes (Key:Value): + address: http://localhost:5149 + OriginalFormat (a.k.a Body): Now listening on: {address} +LogRecord.EventId: 14 +LogRecord.EventName: ListeningOnAddress + +Resource associated with LogRecord: +service.name: TelemetryExample +service.instance.id: 6f6f22d0-8012-45b4-befd-a177eafae2bc +telemetry.sdk.name: opentelemetry +telemetry.sdk.language: dotnet +telemetry.sdk.version: 1.10.0 + +info: Microsoft.Hosting.Lifetime[0] + Application started. Press Ctrl+C to shut down. +LogRecord.Timestamp: 2024-11-19T10:49:38.2432820Z +LogRecord.CategoryName: Microsoft.Hosting.Lifetime +LogRecord.Severity: Info +LogRecord.SeverityText: Information +LogRecord.Body: Application started. Press Ctrl+C to shut down. +LogRecord.Attributes (Key:Value): + OriginalFormat (a.k.a Body): Application started. Press Ctrl+C to shut down. + +Resource associated with LogRecord: +service.name: TelemetryExample +service.instance.id: 6f6f22d0-8012-45b4-befd-a177eafae2bc +telemetry.sdk.name: opentelemetry +telemetry.sdk.language: dotnet +telemetry.sdk.version: 1.10.0 + +LogRecord.Timestamp: 2024-11-19T10:49:38.2439978Z +LogRecord.CategoryName: Microsoft.Hosting.Lifetime +LogRecord.Severity: Info +LogRecord.SeverityText: Information +LogRecord.Body: Hosting environment: {EnvName} +LogRecord.Attributes (Key:Value): +info: Microsoft.Hosting.Lifetime[0] + Hosting environment: Development + EnvName: Development + OriginalFormat (a.k.a Body): Hosting environment: {EnvName} + +Resource associated with LogRecord: +service.name: TelemetryExample +service.instance.id: 6f6f22d0-8012-45b4-befd-a177eafae2bc +telemetry.sdk.name: opentelemetry +telemetry.sdk.language: dotnet +telemetry.sdk.version: 1.10.0 + +info: Microsoft.Hosting.Lifetime[0] + Content root path: /home/pavelresh/college/kontur-backend/telemetry +LogRecord.Timestamp: 2024-11-19T10:49:38.2441789Z +LogRecord.CategoryName: Microsoft.Hosting.Lifetime +LogRecord.Severity: Info +LogRecord.SeverityText: Information +LogRecord.Body: Content root path: {ContentRoot} +LogRecord.Attributes (Key:Value): + ContentRoot: /home/pavelresh/college/kontur-backend/telemetry + OriginalFormat (a.k.a Body): Content root path: {ContentRoot} + +Resource associated with LogRecord: +service.name: TelemetryExample +service.instance.id: 6f6f22d0-8012-45b4-befd-a177eafae2bc +telemetry.sdk.name: opentelemetry +telemetry.sdk.language: dotnet +telemetry.sdk.version: 1.10.0 + +info: Microsoft.Hosting.Lifetime[0] + Application is shutting down... +LogRecord.Timestamp: 2024-11-19T10:49:49.4908074Z +LogRecord.CategoryName: Microsoft.Hosting.Lifetime +LogRecord.Severity: Info +LogRecord.SeverityText: Information +LogRecord.Body: Application is shutting down... +LogRecord.Attributes (Key:Value): + OriginalFormat (a.k.a Body): Application is shutting down... + +Resource associated with LogRecord: +service.name: TelemetryExample +service.instance.id: 6f6f22d0-8012-45b4-befd-a177eafae2bc +telemetry.sdk.name: opentelemetry +telemetry.sdk.language: dotnet +telemetry.sdk.version: 1.10.0 + diff --git a/prometheus.yml b/prometheus.yml new file mode 100644 index 0000000..7bba853 --- /dev/null +++ b/prometheus.yml @@ -0,0 +1,6 @@ +scrape_configs: + - job_name: "prometheus" + # Override the global default and scrape targets from this job every 5 seconds. + scrape_interval: 5s + static_configs: + - targets: [ "host.docker.internal:5149" ] diff --git a/telemetry.csproj b/telemetry.csproj index 1b28a01..63e07f3 100644 --- a/telemetry.csproj +++ b/telemetry.csproj @@ -6,4 +6,14 @@ enable + + + + + + + + + +