Skip to content

Commit c0b2053

Browse files
authored
Merge pull request #44 from PandaTechAM/development
logging options added
2 parents ae754b1 + be682f5 commit c0b2053

File tree

3 files changed

+66
-27
lines changed

3 files changed

+66
-27
lines changed

Readme.md

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -297,15 +297,30 @@ Use the `AddSerilog` extension when building your `WebApplicationBuilder`. You c
297297
In your middleware pipeline, add the request and response logging middleware:
298298

299299
```csharp
300-
var builder = WebApplication.CreateBuilder(args);
301-
302-
// Example: logs in Loki JSON format, keep logs for 14 days. (default = 7 days)
303-
builder.AddSerilog(logBackend: LogBackend.Loki, daysToRetain: 14);
304-
305-
var app = builder.Build();
306-
app.UseRequestLogging();
300+
// 1) Synchronous logging with 7-day retention (default).
301+
builder.AddSerilog(LogBackend.Loki);
302+
303+
// 2) Asynchronous logging with 14-day retention and extra properties.
304+
// Suitable for high-load (~1000+ RPS per pod) scenarios where slight risk of log loss is acceptable
305+
// in exchange for better performance.
306+
builder.AddSerilog(
307+
logBackend: LogBackend.Loki,
308+
logAdditionalProperties: new Dictionary<string, string>
309+
{
310+
["ServiceName"] = "MyApp",
311+
["Environment"] = "Staging"
312+
},
313+
daysToRetain: 14,
314+
asyncSinks: true
315+
);
307316
```
308317

318+
>- **Asynchronous Sinks (asyncSinks: true):** Recommended for very high-traffic environments (e.g., 1000+ requests per
319+
second per pod) where performance is critical and the possibility of losing a small amount of log data (e.g., on
320+
sudden process termination) is acceptable. <br><br>
321+
>- **Synchronous Sinks (asyncSinks: false):** Recommended if you can handle up to ~1000 requests per second per pod and must
322+
retain every log entry without fail. This might incur slightly more overhead but ensures maximum reliability.
323+
309324
Configure minimal Serilog settings in your environment JSON files as needed, for example in
310325
`appsettings.{Environment}.json`:
311326

@@ -342,7 +357,7 @@ hosted service runs periodically to delete log files older than the specified re
342357
```csharp
343358
builder.AddSerilog(
344359
logBackend: LogBackend.Loki,
345-
valueByNameRepeatedLog: new Dictionary<string, string>
360+
logAdditionalProperties: new Dictionary<string, string>
346361
{
347362
{"ServiceName", "MyService"},
348363
{"ServiceVersion", "1.0.0"}

src/SharedKernel/Logging/SerilogExtensions.cs

Lines changed: 41 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using System.Diagnostics;
2-
using Elastic.CommonSchema.Serilog;
1+
using Elastic.CommonSchema.Serilog;
32
using Microsoft.AspNetCore.Builder;
43
using Microsoft.Extensions.DependencyInjection;
54
using Microsoft.Extensions.Hosting;
@@ -17,22 +16,23 @@ public static class SerilogExtensions
1716
{
1817
public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builder,
1918
LogBackend logBackend,
19+
Dictionary<string, string>? logAdditionalProperties = null,
2020
int daysToRetain = 7,
21-
Dictionary<string, string>? valueByNameRepeatedLog = null)
21+
bool asyncSinks = false)
2222
{
2323
builder.Logging.ClearProviders();
2424

2525
var loggerConfig = new LoggerConfiguration()
2626
.FilterOutUnwantedLogs()
2727
.Enrich
2828
.FromLogContext()
29-
.ConfigureDestinations(builder, logBackend)
29+
.ConfigureDestinations(builder, logBackend, asyncSinks)
3030
.ReadFrom
3131
.Configuration(builder.Configuration);
3232

33-
if (valueByNameRepeatedLog is not null)
33+
if (logAdditionalProperties is not null)
3434
{
35-
foreach (var (key, value) in valueByNameRepeatedLog)
35+
foreach (var (key, value) in logAdditionalProperties)
3636
{
3737
loggerConfig.Enrich.WithProperty(key, value);
3838
}
@@ -60,30 +60,47 @@ public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builde
6060

6161
private static LoggerConfiguration ConfigureDestinations(this LoggerConfiguration loggerConfig,
6262
WebApplicationBuilder builder,
63-
LogBackend logBackend)
63+
LogBackend logBackend,
64+
bool asyncSinks)
6465
{
6566
if (builder.Environment.IsLocal())
6667
{
67-
loggerConfig.WriteTo.Async(a => a.Console());
68+
loggerConfig.WriteToConsole(asyncSinks);
69+
6870
return loggerConfig;
6971
}
7072

7173
if (!builder.Environment.IsProduction())
7274
{
73-
loggerConfig.WriteTo.Async(a => a.Console());
75+
loggerConfig.WriteToConsole(asyncSinks);
7476
}
7577

7678
if (logBackend != LogBackend.None)
7779
{
78-
loggerConfig.WriteToFileAsync(builder, logBackend);
80+
loggerConfig.WriteToFile(builder, logBackend, asyncSinks);
7981
}
8082

8183
return loggerConfig;
8284
}
8385

84-
private static LoggerConfiguration WriteToFileAsync(this LoggerConfiguration loggerConfig,
86+
private static LoggerConfiguration WriteToConsole(this LoggerConfiguration loggerConfig, bool useAsync)
87+
{
88+
if (useAsync)
89+
{
90+
loggerConfig.WriteTo.Async(a => a.Console());
91+
}
92+
else
93+
{
94+
loggerConfig.WriteTo.Console();
95+
}
96+
97+
return loggerConfig;
98+
}
99+
100+
private static LoggerConfiguration WriteToFile(this LoggerConfiguration loggerConfig,
85101
WebApplicationBuilder builder,
86-
LogBackend logBackend)
102+
LogBackend logBackend,
103+
bool useAsync)
87104
{
88105
// Choose the formatter based on the selected log backend
89106
ITextFormatter formatter = logBackend switch
@@ -94,11 +111,18 @@ private static LoggerConfiguration WriteToFileAsync(this LoggerConfiguration log
94111
_ => new CompactJsonFormatter() // Fallback
95112
};
96113

97-
return loggerConfig.WriteTo.Async(a =>
98-
a.File(formatter,
99-
builder.GetLogsPath(),
100-
rollingInterval: RollingInterval.Day)
101-
);
114+
var logPath = builder.GetLogsPath();
115+
116+
if (useAsync)
117+
{
118+
return loggerConfig.WriteTo.Async(a =>
119+
a.File(formatter,
120+
logPath,
121+
rollingInterval: RollingInterval.Day)
122+
);
123+
}
124+
125+
return loggerConfig.WriteTo.File(formatter, logPath, rollingInterval: RollingInterval.Day);
102126
}
103127

104128
#region Filtering

src/SharedKernel/SharedKernel.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
<PackageReadmeFile>Readme.md</PackageReadmeFile>
99
<Authors>Pandatech</Authors>
1010
<Copyright>MIT</Copyright>
11-
<Version>1.3.1</Version>
11+
<Version>1.3.2</Version>
1212
<PackageId>Pandatech.SharedKernel</PackageId>
1313
<Title>Pandatech Shared Kernel Library</Title>
1414
<PackageTags>Pandatech, shared kernel, library, OpenAPI, Swagger, utilities, scalar</PackageTags>
1515
<Description>Pandatech.SharedKernel provides centralized configurations, utilities, and extensions for ASP.NET Core projects. For more information refere to readme.md document.</Description>
1616
<RepositoryUrl>https://github.com/PandaTechAM/be-lib-sharedkernel</RepositoryUrl>
17-
<PackageReleaseNotes>Added compact json support to log backend</PackageReleaseNotes>
17+
<PackageReleaseNotes>Made sync and async optional in logging</PackageReleaseNotes>
1818
</PropertyGroup>
1919

2020
<ItemGroup>

0 commit comments

Comments
 (0)