-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
304 lines (268 loc) · 14 KB
/
Program.cs
File metadata and controls
304 lines (268 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using GiddhTemplate.Services;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Formatting.Json;
using OpenTelemetry.Trace;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Exporter;
using System.Diagnostics;
public class Program
{
public static async Task Main(string[] args)
{
// ===========================================
// GLOBAL FALLBACK EXCEPTION HANDLERS (EARLY)
// ===========================================
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Log.Fatal(e.ExceptionObject as Exception, "Unhandled (domain)");
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task");
e.SetObserved();
};
// Load configuration early
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
optional: true)
.AddEnvironmentVariables()
.Build();
var grafanaEnv = Environment.GetEnvironmentVariable("GRAFANA_APP_ENV");
if (!string.IsNullOrEmpty(grafanaEnv))
{
configuration["Serilog:WriteTo:2:Args:labels:1:value"] = grafanaEnv;
}
var serviceVersion = Environment.GetEnvironmentVariable("APP_VERSION") ?? "1.0.0";
var environmentName = Environment.GetEnvironmentVariable("GRAFANA_APP_ENV")
?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
?? "Development";
var slackEnvironment = Environment.GetEnvironmentVariable("ENVIRONMENT") ?? environmentName;
var serviceName = Environment.GetEnvironmentVariable("SERVICE_NAME") ?? "giddh-template";
var serviceType = Environment.GetEnvironmentVariable("GRAFANA_SERVICE_TYPE") ?? "api";
var company = Environment.GetEnvironmentVariable("GRAFANA_COMPANY") ?? "Walkover";
var product = Environment.GetEnvironmentVariable("GRAFANA_PRODUCT") ?? "GIDDH";
var serverRegion = Environment.GetEnvironmentVariable("SERVER_REGION") ?? "IN";
var orgId = Environment.GetEnvironmentVariable("GRAFANA_ORG_ID");
// ===========================================
// CENTRALIZED SERILOG WITH STRUCTURED JSON LOGGING
// ===========================================
var logFilePath = "/var/log/template-logs/giddh-template.log";
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentName()
.Enrich.WithProcessId()
.Enrich.WithThreadId()
.Enrich.WithMachineName()
.Enrich.WithProperty("Application", "GiddhTemplateService")
.Enrich.WithProperty("Version", serviceVersion)
.Enrich.WithProperty("Service", serviceName)
.Enrich.WithProperty("ServiceType", serviceType)
.Enrich.WithProperty("Environment", environmentName)
.Enrich.WithProperty("Company", company)
.Enrich.WithProperty("Product", product)
.WriteTo.Console(new JsonFormatter())
.WriteTo.File(new JsonFormatter(), logFilePath, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 30)
.CreateLogger();
try
{
Log.Information("Starting GIDDH Template Service...");
var builder = WebApplication.CreateBuilder(args);
// Prevent duplicate logs
builder.Logging.ClearProviders();
builder.Host.UseSerilog();
// ===========================================
// OPENTELEMETRY SETUP
// ===========================================
var openTelemetry = builder.Services.AddOpenTelemetry();
openTelemetry.ConfigureResource(resource =>
resource.AddService(
serviceName: serviceName,
serviceVersion: serviceVersion,
serviceInstanceId: Environment.MachineName)
.AddAttributes(new KeyValuePair<string, object>[]
{
new("deployment.environment", environmentName),
new("company", company),
new("product", product),
new("service.type", serviceType),
new("service.namespace", product),
new("service.instance.id", Environment.MachineName),
new("server.region", serverRegion)
}));
openTelemetry.WithTracing(tracing =>
{
tracing
.SetSampler(new AlwaysOnSampler())
.AddAspNetCoreInstrumentation(options =>
{
options.RecordException = true;
})
.AddHttpClientInstrumentation()
.AddSource("GiddhTemplate.*")
.AddOtlpExporter(options =>
{
options.Endpoint = new Uri("http://127.0.0.1:4318/v1/traces");
options.Protocol = OtlpExportProtocol.HttpProtobuf;
if (!string.IsNullOrWhiteSpace(orgId))
{
options.Headers = $"X-Scope-OrgID={orgId}";
}
});
});
openTelemetry.WithMetrics(metrics =>
{
metrics
.AddAspNetCoreInstrumentation()
.AddRuntimeInstrumentation()
.AddMeter("GiddhTemplate.Metrics")
.AddPrometheusExporter();
});
// Dependency injection
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ISlackService, SlackService>();
builder.Services.AddSingleton<RazorTemplateService>();
builder.Services.AddSingleton<PdfService>();
builder.Services.AddScoped<AccountStatementPdfService>();
builder.Services.AddHostedService<MemoryReservationService>();
builder.Services.AddHostedService<PdfCleanupService>();
builder.Services.AddControllers();
var app = builder.Build();
// Pre-warm browser on startup
var pdfService = app.Services.GetRequiredService<PdfService>();
await pdfService.GetBrowserAsync();
// Register browser disposal on shutdown
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
PdfService.DisposeBrowserAsync().GetAwaiter().GetResult();
});
// ===========================================
// CENTRALIZED GLOBAL EXCEPTION HANDLER WITH RICH CONTEXT
// ===========================================
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async ctx =>
{
var exceptionDetails = ctx.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerPathFeature>();
if (exceptionDetails?.Error is Exception ex)
{
// Capture rich context for centralized logging
var userAgent = ctx.Request.Headers["User-Agent"].FirstOrDefault() ?? "Unknown";
var remoteIp = ctx.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
var method = ctx.Request.Method;
var route = ctx.Request.Path.Value ?? "unknown";
var queryString = ctx.Request.QueryString.Value ?? "";
// Get distributed tracing context
var activity = Activity.Current;
var traceId = activity?.TraceId.ToString() ?? ctx.TraceIdentifier;
var spanId = activity?.SpanId.ToString() ?? "N/A";
// Centralized structured logging with rich context
Log.Error(ex,
"Unhandled exception | Route: {Route} | Method: {Method} | TraceId: {TraceId} | SpanId: {SpanId} | UserAgent: {UserAgent} | RemoteIP: {RemoteIP} | Query: {QueryString}",
route, method, traceId, spanId, userAgent, remoteIp, queryString);
// Add exception to OpenTelemetry trace with context
activity?.AddEvent(new ActivityEvent("exception", DateTimeOffset.UtcNow, new ActivityTagsCollection
{
["exception.type"] = ex.GetType().FullName ?? "Unknown",
["exception.message"] = ex.Message,
["exception.stacktrace"] = ex.ToString(),
["http.method"] = method,
["http.route"] = route,
["http.user_agent"] = userAgent,
["http.remote_ip"] = remoteIp,
["http.status_code"] = "500"
}));
// Centralized Slack alerting with context
try
{
var slackService = ctx.RequestServices.GetRequiredService<ISlackService>();
var errorContext = $"**Route:** {route} {method}\n**TraceId:** {traceId}\n**UserAgent:** {userAgent}\n**RemoteIP:** {remoteIp}";
await slackService.SendErrorAlertAsync(
route,
slackEnvironment,
$"{ex.GetType().Name}: {ex.Message}\n\n{errorContext}",
ex.StackTrace ?? "No stack trace available");
}
catch (Exception slackEx)
{
Log.Warning(slackEx, "Failed to send Slack alert for {Route} {Method}", route, method);
}
}
ctx.Response.StatusCode = 500;
ctx.Response.ContentType = "application/json";
await ctx.Response.WriteAsJsonAsync(new
{
error = "Internal Server Error",
traceId = ctx.TraceIdentifier,
timestamp = DateTimeOffset.UtcNow
});
});
});
// ===========================================
// CENTRALIZED HTTP REQUEST LOGGING WITH RICH CONTEXT
// ===========================================
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} → {StatusCode} ({Elapsed:0.0000}ms) [{ContentLength}b] | TraceId: {TraceId}";
options.GetLevel = (httpContext, elapsed, ex) =>
{
if (ex != null || httpContext.Response.StatusCode >= 500)
return Serilog.Events.LogEventLevel.Error;
if (httpContext.Response.StatusCode >= 400)
return Serilog.Events.LogEventLevel.Warning;
if (elapsed > 5000) // Log slow requests as warnings for performance monitoring
return Serilog.Events.LogEventLevel.Warning;
return Serilog.Events.LogEventLevel.Information;
};
options.EnrichDiagnosticContext = (diagCtx, httpContext) =>
{
// Request context
diagCtx.Set("RequestHost", httpContext.Request.Host.Value);
diagCtx.Set("RequestScheme", httpContext.Request.Scheme);
diagCtx.Set("QueryString", httpContext.Request.QueryString.Value);
// Client context
diagCtx.Set("UserAgent", httpContext.Request.Headers["User-Agent"].FirstOrDefault() ?? "Unknown");
diagCtx.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress?.ToString() ?? "Unknown");
diagCtx.Set("Referer", httpContext.Request.Headers["Referer"].FirstOrDefault());
// Response context
diagCtx.Set("ContentLength", httpContext.Response.ContentLength ?? 0);
diagCtx.Set("ContentType", httpContext.Response.ContentType);
// Distributed tracing context
var activity = Activity.Current;
if (activity != null)
{
diagCtx.Set("TraceId", activity.TraceId.ToString());
diagCtx.Set("SpanId", activity.SpanId.ToString());
diagCtx.Set("ParentId", activity.ParentId);
}
// Performance context
diagCtx.Set("RequestStartTime", DateTimeOffset.UtcNow);
};
});
app.MapPrometheusScrapingEndpoint();
app.MapControllers();
Log.Information("GIDDH Template Service started successfully on port 5000");
await app.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "GIDDH Template Service terminated unexpectedly");
throw;
}
finally
{
Log.Information("GIDDH Template Service is shutting down...");
await Log.CloseAndFlushAsync();
}
}
private static Uri? TryCreateUri(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
return Uri.TryCreate(value, UriKind.Absolute, out var uri) ? uri : null;
}
}