feat: 集成OpenTelemetry埋点与日志输出

This commit is contained in:
2025-12-02 13:27:43 +08:00
parent fcce44b767
commit 753c10c492
12 changed files with 343 additions and 27 deletions

View File

@@ -5,6 +5,9 @@ using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Serilog;
using TakeoutSaaS.Application.App.Extensions;
using TakeoutSaaS.Application.Identity.Extensions;
@@ -34,7 +37,12 @@ builder.Host.UseSerilog((context, _, configuration) =>
configuration
.Enrich.FromLogContext()
.Enrich.WithProperty("Service", "AdminApi")
.WriteTo.Console();
.WriteTo.Console()
.WriteTo.File(
"logs/admin-api-.log",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
shared: true);
});
builder.Services.AddSharedWebCore();
@@ -60,6 +68,59 @@ builder.Services.AddSmsApplication(builder.Configuration);
builder.Services.AddMessagingModule(builder.Configuration);
builder.Services.AddMessagingApplication();
builder.Services.AddSchedulerModule(builder.Configuration);
var otelSection = builder.Configuration.GetSection("Otel");
var otelEndpoint = otelSection.GetValue<string>("Endpoint");
var useConsoleExporter = otelSection.GetValue<bool?>("UseConsoleExporter") ?? builder.Environment.IsDevelopment();
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(
serviceName: "TakeoutSaaS.AdminApi",
serviceVersion: "1.0.0",
serviceInstanceId: Environment.MachineName))
.WithTracing(tracing =>
{
tracing
.SetSampler(new ParentBasedSampler(new AlwaysOnSampler()))
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddEntityFrameworkCoreInstrumentation(options =>
{
options.SetDbStatementForText = false;
options.SetDbStatementForStoredProcedure = false;
});
if (!string.IsNullOrWhiteSpace(otelEndpoint))
{
tracing.AddOtlpExporter(exporter =>
{
exporter.Endpoint = new Uri(otelEndpoint);
});
}
if (useConsoleExporter)
{
tracing.AddConsoleExporter();
}
})
.WithMetrics(metrics =>
{
metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
if (!string.IsNullOrWhiteSpace(otelEndpoint))
{
metrics.AddOtlpExporter(exporter =>
{
exporter.Endpoint = new Uri(otelEndpoint);
});
}
if (useConsoleExporter)
{
metrics.AddConsoleExporter();
}
});
var adminOrigins = ResolveCorsOrigins(builder.Configuration, "Cors:Admin");
builder.Services.AddCors(options =>