Skip to content

Commit b885f73

Browse files
committed
Add Serilog, Prometheus and Grafana for logging and monitoring
1 parent 7eb0878 commit b885f73

21 files changed

+270
-73
lines changed

AttachmentService/Dockerfile

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
2+
3+
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
4+
WORKDIR /app
5+
EXPOSE 80
6+
EXPOSE 443
7+
8+
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
9+
WORKDIR /src
10+
COPY ["AttachmentService/AttachmentService.csproj", "AttachmentService/"]
11+
RUN dotnet restore "AttachmentService/AttachmentService.csproj"
12+
COPY . .
13+
WORKDIR "/src/AttachmentService"
14+
RUN dotnet build "AttachmentService.csproj" -c Release -o /app/build
15+
16+
FROM build AS publish
17+
RUN dotnet publish "AttachmentService.csproj" -c Release -o /app/publish /p:UseAppHost=false
18+
19+
FROM base AS final
20+
WORKDIR /app
21+
COPY --from=publish /app/publish .
22+
ENTRYPOINT ["dotnet", "AttachmentService.dll"]

FrontendService/FrontendService/Controllers/LoginController.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public async Task<IActionResult> Login(LoginViewModel model)
5050

5151
if (response.IsSuccessStatusCode)
5252
{
53-
_logger.LogInformation("Response from Auth/UserService is success.");
53+
_logger.LogWarning("Response from Auth/UserService is success.");
5454
var responseData = await response.Content.ReadAsStringAsync();
5555

5656
var options = new JsonSerializerOptions
@@ -80,22 +80,22 @@ public async Task<IActionResult> Login(LoginViewModel model)
8080
Response.Cookies.Append("UserId", userId, cookieOptions);
8181

8282
ViewDataMsg = "";
83-
_logger.LogInformation("Token, UserName, UserId successfully added to the cookies.");
83+
_logger.LogWarning("Token, UserName, UserId successfully added to the cookies.");
8484
return RedirectToAction("Index", "Post");
8585
}
8686
else
8787
{
88-
_logger.LogInformation("jsonToken is null.");
88+
_logger.LogWarning("jsonToken is null.");
8989
}
9090
}
9191
else
9292
{
93-
_logger.LogInformation("Token is null.");
93+
_logger.LogWarning("Token is null.");
9494
}
9595
}
9696
else
9797
{
98-
_logger.LogInformation($"Response from Auth/UserService is not success. Status code: {response.StatusCode}.");
98+
_logger.LogWarning($"Response from Auth/UserService is not success. Status code: {response.StatusCode}.");
9999
}
100100
}
101101
catch (Exception ex)
@@ -105,7 +105,7 @@ public async Task<IActionResult> Login(LoginViewModel model)
105105
}
106106
else
107107
{
108-
_logger.LogInformation("ModelState is not valid for login.");
108+
_logger.LogWarning("ModelState is not valid for login.");
109109
}
110110

111111
ViewDataMsg = "Wrong credentials, Please try again.";

FrontendService/FrontendService/Controllers/PostController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public async Task<IActionResult> Index()
3030
}
3131
else
3232
{
33-
_logger.LogInformation("Getting Posts from Post service is not successfull. Redirecting to the Login page.");
33+
_logger.LogWarning("Getting Posts from Post service is not successfull. Redirecting to the Login page.");
3434
return RedirectToAction("Index", "Login");
3535
}
3636
}

FrontendService/FrontendService/FrontendService.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111
<ItemGroup>
1212
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
1313
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" />
14+
<PackageReference Include="prometheus-net.AspNetCore" Version="7.0.0" />
15+
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
16+
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
17+
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="10.0.0" />
18+
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
1419
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.2" />
1520
<PackageReference Include="Yarp.ReverseProxy" Version="2.2.0" />
1621
</ItemGroup>

FrontendService/FrontendService/Program.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
using FrontendService.Services;
2+
using Prometheus;
3+
using Serilog;
4+
5+
// Configure Serilog
6+
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
7+
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
28

39
var builder = WebApplication.CreateBuilder(args);
410

11+
// Replace default logging with Serilog
12+
builder.Host.UseSerilog();
13+
514
// Add services to the container
615
builder.Services.AddControllersWithViews();
716
builder.Services.AddHttpClient();
@@ -13,6 +22,10 @@
1322

1423
var app = builder.Build();
1524

25+
// Add Prometheus metrics endpoint
26+
app.UseHttpMetrics(); // Collect HTTP metrics like request count, duration, etc.
27+
app.MapMetrics("/metrics"); // Expose metrics at /metrics endpoint
28+
1629
if (!app.Environment.IsDevelopment())
1730
{
1831
app.UseExceptionHandler("/Home/Error");
@@ -34,4 +47,16 @@
3447
// Map YARP reverse proxy
3548
app.MapReverseProxy();
3649

37-
app.Run();
50+
try
51+
{
52+
Log.Information("Starting the application...");
53+
app.Run();
54+
}
55+
catch (Exception ex)
56+
{
57+
Log.Fatal(ex, "Application start-up failed!");
58+
}
59+
finally
60+
{
61+
Log.CloseAndFlush(); // Ensure all logs are flushed on shutdown
62+
}

FrontendService/FrontendService/appsettings.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,30 @@
4646
}
4747
}
4848
}
49+
},
50+
"Serilog": {
51+
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
52+
"MinimumLevel": {
53+
"Default": "Warning",
54+
"Override": {
55+
"Microsoft": "Warning",
56+
"System": "Warning",
57+
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
58+
}
59+
},
60+
"WriteTo": [
61+
{
62+
"Name": "Console"
63+
},
64+
{
65+
"Name": "File",
66+
"Args": {
67+
"path": "logs/FrontendServiceLog-.txt",
68+
"rollingInterval": "Day",
69+
"retainedFileCountLimit": 7
70+
}
71+
}
72+
],
73+
"Enrich": [ "FromLogContext" ]
4974
}
5075
}

FrontendService/docker-compose.yml

Lines changed: 0 additions & 15 deletions
This file was deleted.

PostService/PostService/Controllers/PostsController.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public PostsController(ILogger<PostsController> logger, PostServiceContext conte
2727
public async Task<ActionResult<IEnumerable<Post>>> GetPost()
2828
{
2929
var isValid = await ValidToken();
30-
_logger.LogInformation($"Value of isValid in the GetPost method: {isValid}.");
30+
_logger.LogWarning($"Value of isValid in the GetPost method: {isValid}.");
3131
if (isValid)
3232
{
3333
if (_context.Post == null)
@@ -158,7 +158,7 @@ private bool PostExists(int id)
158158
private async Task<bool> ValidToken()
159159
{
160160
var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
161-
_logger.LogInformation($"Token in the ValidToken method: {token}.");
161+
_logger.LogWarning($"Token in the ValidToken method: {token}.");
162162

163163
if (string.IsNullOrEmpty(token))
164164
{

PostService/PostService/PostService.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@
1818
</PackageReference>
1919
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
2020
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" />
21+
<PackageReference Include="prometheus-net.AspNetCore" Version="7.0.0" />
2122
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
23+
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
24+
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
25+
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="10.0.0" />
26+
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
2227
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
2328
</ItemGroup>
2429

PostService/PostService/Program.cs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
using Microsoft.EntityFrameworkCore;
22
using PostService.Data;
33
using PostService.Services;
4+
using Prometheus;
5+
using Serilog;
6+
7+
// Configure Serilog
8+
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
9+
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
410

511
var builder = WebApplication.CreateBuilder(args);
12+
13+
// Replace default logging with Serilog
14+
builder.Host.UseSerilog();
15+
616
builder.Services.AddDbContext<PostServiceContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("PostDB")));
717
builder.Services.AddControllers();
818
builder.Services.AddEndpointsApiExplorer();
@@ -15,6 +25,10 @@
1525

1626
var app = builder.Build();
1727

28+
// Add Prometheus metrics endpoint
29+
app.UseHttpMetrics(); // Collect HTTP metrics like request count, duration, etc.
30+
app.MapMetrics("/metrics"); // Expose metrics at /metrics endpoint
31+
1832
//Apply pending migrations on startup
1933
//using (var scope = app.Services.CreateScope())
2034
//{
@@ -34,4 +48,16 @@
3448

3549
app.MapControllers();
3650

37-
app.Run();
51+
try
52+
{
53+
Log.Information("Starting the application...");
54+
app.Run();
55+
}
56+
catch (Exception ex)
57+
{
58+
Log.Fatal(ex, "Application start-up failed!");
59+
}
60+
finally
61+
{
62+
Log.CloseAndFlush(); // Ensure all logs are flushed on shutdown
63+
}

0 commit comments

Comments
 (0)