Compare commits

...
4 Commits
Author SHA1 Message Date
saherelm 2308ec0be3 Refactor File Log Writer to Use Data yyy-MM-DD in File Name ... 2026-11-12 20:18:54 +03:30
saherelm def0807fdd 2.1) Middleware جدید
- فایل: MIddlewares/XRequestLoggingMiddleware.cs (NEW)
- ویژگی: Simple/Full logging modes
- قابلیت: HTTP request/response logging، exception handling

⚠️ توجه: نام پوشه "MIddlewares" typo است - باید تصحیح شود

2.2) توسعه DI
- متد: AddXTelemetryLogger() - logging configuration
- متد: AddXTelemetry() - host builder extension
- متد: UseXRequestLogger() - middleware registration

2.3) به‌روزرسانی Dependencies
- OpenTelemetry.Extensions.Hosting v1.6.0
- OpenTelemetry.Instrumentation.Http v1.6.0
- OpenTelemetry.Instrumentation.AspNetCore v1.6.0
- OpenTelemetry.Exporter.OpenTelemetryProtocol v1.6.0
- Microsoft.Extensions.Logging.Console v5.0.0
2026-11-09 12:50:04 +03:30
saherelm 0fe37483bc last ... 2026-11-08 22:54:50 +03:30
saherelm 777ceaa8f0 last ... 2026-11-08 18:06:35 +03:30
4 changed files with 410 additions and 10 deletions
+139 -4
View File
@@ -1,16 +1,22 @@
using System;
using OpenTelemetry.Logs;
using OpenTelemetry.Trace;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants; using xExceptions.Constants;
using OpenTelemetry.Resources;
using xLoggingService.Writers; using xLoggingService.Writers;
using xEventService.Interfaces; using xEventService.Interfaces;
using xLoggingService.Providers; using xLoggingService.Providers;
using System.Collections.Generic; using xLoggingService.Constants;
using xLoggingService.Interfaces; using xLoggingService.Interfaces;
using xLoggingService.MIddlewares;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using xLoggingService.Configuration; using xLoggingService.Configuration;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System; using Microsoft.Extensions.DependencyInjection.Extensions;
using xLoggingService.Constants;
namespace xLoggingService.DI namespace xLoggingService.DI
{ {
@@ -84,7 +90,7 @@ namespace xLoggingService.DI
/// <param name="source"></param> /// <param name="source"></param>
/// <param name="configuration"></param> /// <param name="configuration"></param>
public static void AddXLoggingService( public static void AddXLoggingService(
this IServiceCollection source, this IServiceCollection source,
IConfiguration configuration IConfiguration configuration
) )
{ {
@@ -96,6 +102,78 @@ namespace xLoggingService.DI
); );
} }
/// <summary>
/// Enable Telemetry Service on Logging ...
/// </summary>
/// <param name="builder"></param>
public static void AddXTelemetryLogger(
this ILoggingBuilder builder
)
{
//
AppContext.SetSwitch(
"System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
//
// Clear Providers ...
builder.ClearProviders();
builder.AddConsole();
builder.AddOpenTelemetry(options =>
{
//
options.SetResourceBuilder(
ResourceBuilder
.CreateDefault()
.AddService(nameof(xLoggingService)));
//
options.AddOtlpExporter();
});
}
/// <summary>
/// Add Telemetry Service to Services ...
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IHostBuilder AddXTelemetry(
this IHostBuilder builder
)
{
//
// Configure Services ...
builder = builder
.ConfigureServices((hostContext, services) =>
{
//
services
.AddOpenTelemetry()
.ConfigureResource(resource =>
resource.AddService(nameof(xLoggingService)))
.WithTracing(tracing =>
tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter());
});
//
return builder;
}
/// <summary>
/// Use Request Logging Middleware ...
/// Log all Requests, and it's Flow to Logger ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static IApplicationBuilder UseXRequestLogger(
this IApplicationBuilder source
)
{
return source.UseMiddleware<XRequestLoggingMiddleware>();
}
// //
#region Private #region Private
/// <summary> /// <summary>
@@ -112,6 +190,12 @@ namespace xLoggingService.DI
Console.WriteLine($"{XLogTag} => {message}"); Console.WriteLine($"{XLogTag} => {message}");
} }
/// <summary>
/// Register Logging Service ...
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <param name="lifeTime"></param>
private static void AddLoggingService( private static void AddLoggingService(
this IServiceCollection services, this IServiceCollection services,
XLoggingServiceConfiguration configuration, XLoggingServiceConfiguration configuration,
@@ -126,11 +210,62 @@ namespace xLoggingService.DI
Log($"Invalid Service Lifetime ..."); Log($"Invalid Service Lifetime ...");
XException.InvalidArgs.Throw(); XException.InvalidArgs.Throw();
} }
// //
// Register Service Configuration ... // Register Service Configuration ...
services.AddXLoggingServiceConfiguration(configuration); services.AddXLoggingServiceConfiguration(configuration);
// //
// File Log Provider ...
if (configuration.File.Enabled)
{
//
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IXLogWriter, XFileLogWriter>());
//
Log("FileLogWriter registered.");
}
//
// Database Log Provider ...
if (configuration.Database.Enabled)
{
//
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IXLogWriter, XDatabaseLogWriter>());
//
Log("DatabaseLogWriter registered.");
}
//
// Event Service Provider ...
if (configuration.Event.Enabled)
{
//
var eventService = services.GetRegisteredService<IXEventServiceProvider>();
if (eventService.IsNull())
{
//
Log("Event Service not Provided ...");
XException.InvalidConfiguration.Throw();
}
//
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IXLogWriter, XEventLogWriter>());
//
Log("EventLogWriter registered.");
}
//
services.TryAddEnumerable(
ServiceDescriptor.Singleton<ILoggerProvider, XLoggerProvider>());
//
Log($"Logging Service registered successfully ...");
} }
#endregion #endregion
} }
+259
View File
@@ -0,0 +1,259 @@
using System;
using System.IO;
using xCommons.Models;
using System.Diagnostics;
using xCommons.Extensions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace xLoggingService.MIddlewares
{
public class XRequestLoggingMiddleware
{
//
private readonly RequestDelegate next;
private readonly bool useSimpleLogging = false;
private readonly ILogger<XRequestLoggingMiddleware> logger;
public XRequestLoggingMiddleware(
RequestDelegate next,
ILogger<XRequestLoggingMiddleware> logger
)
{
//
this.next = next;
this.logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
//
if (useSimpleLogging)
{
await InvokeAsyncSimple(context);
}
else
{
await InvokeAsyncFull(context);
}
}
public async Task InvokeAsyncSimple(HttpContext context)
{
//
var stopwatch = Stopwatch.StartNew();
try
{
//
// Logging Request Start ...
logger.LogInformation(
"Handling request: {Method} {Path}",
context.Request.Method,
context.Request.Path
);
//
// Handling Request ...
await next(context);
//
// Logging Request End ...
stopwatch.Stop();
logger.LogInformation(
"Finished handling request: {Method} {Path} in {Elapsed}ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds
);
}
catch (Exception ex)
{
//
// Logging Request Error ...
stopwatch.Stop();
logger.LogError(ex,
"Request failed: {Method} {Path} after {Elapsed}ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds
);
//
// Throw Exception Agains for Handling using Top Level Middlewares ...
throw;
}
}
public async Task InvokeAsyncFull(HttpContext context)
{
//
var stopwatch = Stopwatch.StartNew();
try
{
//
// Logging Request Start ...
logger.LogInformation(
"Handling request: {Method} {Path}",
context.Request.Method,
context.Request.Path
);
//
var logModel = new XLoggerModel();
//
logModel.Path = context.Request.Path;
logModel.Schema = context.Request.Scheme;
logModel.Method = context.Request.Method;
logModel.Headers = context.Request.Headers;
logModel.Host = context.Request.Host.ToString();
logModel.QueryString = context.Request.QueryString.ToString();
logModel.UserID = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Not Authenticated";
//
logModel.Connection = new XLoggerHttpConnection
{
Id = context.Connection.Id,
RemoteIpAddress = context.Connection.RemoteIpAddress.ToString(),
RemotePort = context.Connection.RemotePort.ToString(),
LocalIpAddress = context.Connection.LocalIpAddress.ToString(),
LocalPort = context.Connection.LocalPort.ToString(),
};
//
// Check if a request is a Post Call so read data from Body ...
if (context.Request.Method.ToNormalString() == "post")
{
//
context.Request.EnableBuffering();
var request = await new StreamReader(context.Request.Body)
.ReadToEndAsync();
//
context.Request.Body.Position = 0;
logModel.Request = request;
}
//
logModel.RequestedOn = DateTime.UtcNow;
//
// Do Request ...
await next.Invoke(context);
//
using (Stream originalRequest = context.Response.Body)
{
try
{
//
using (var memStream = new MemoryStream())
{
//
context.Response.Body = memStream;
//
// All the Request processing as described above
// happens from here.
// Response handling starts from here
// set the pointer to the beginning of the
// memory stream to read
memStream.Position = 0;
//
// read the memory stream till the end
var response = await new StreamReader(memStream)
.ReadToEndAsync();
//
logModel.Response = response;
logModel.RespondedOn = DateTime.UtcNow;
logModel.StatusCode = context.Response.StatusCode;
logModel.IsSucceed = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;
//
// since we have read till the end of the stream,
// reset it onto the first position
memStream.Position = 0;
//
// now copy the content of the temporary memory
// stream we have passed to the actual response body
// which will carry the response out.
await memStream.CopyToAsync(originalRequest);
}
}
catch (Exception ex)
{
//
// Log Exception ...
logModel.Exception = ex;
logger.LogError($"Error on Logging Request/Response ... {ex.ToJSON()}");
}
finally
{
//
// assign the response body to the actual context
logModel.RespondedOn = DateTime.UtcNow;
context.Response.Body = originalRequest;
}
}
//
// Logging Request End ...
stopwatch.Stop();
logger.LogInformation(
"Finished handling request: {Method} {Path} in {Elapsed}ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds
);
//
// Log Response ...
logger.LogCritical($"Http Response/Response Information:{Environment.NewLine}" +
$"Schema:{logModel.Schema} " + Environment.NewLine +
$"Host: {logModel.Host} " + Environment.NewLine +
$"Path: {logModel.Path} " + Environment.NewLine +
$"Method: {logModel.Method} " + Environment.NewLine +
$"UserID: {logModel.UserID} " + Environment.NewLine +
$"QueryString: {context.Request.QueryString} " + Environment.NewLine +
$"Headers: {logModel.Headers.ToJSON()}" + Environment.NewLine +
$"" + Environment.NewLine +
$"Http Connection: " + Environment.NewLine +
$"Id: {logModel.Connection.Id}" + Environment.NewLine +
$"RemoteIpAddress: {logModel.Connection.RemoteIpAddress}" + Environment.NewLine +
$"RemotePort: {logModel.Connection.RemotePort}" + Environment.NewLine +
$"LocalIpAddress: {logModel.Connection.LocalIpAddress}" + Environment.NewLine +
$"LocalPort: {logModel.Connection.LocalPort}" + Environment.NewLine +
$"" + Environment.NewLine +
$"Request Body: {logModel.Request}" + Environment.NewLine +
$"RequestedOn: {logModel.RequestedOn}" + Environment.NewLine +
$"" + Environment.NewLine +
$"IsSucceed: {logModel.IsSucceed}" + Environment.NewLine +
$"StatucCode: {logModel.StatusCode}" + Environment.NewLine +
$"Response Body: {logModel.Response}" + Environment.NewLine +
$"RespondedOn: {logModel.RespondedOn}" + Environment.NewLine +
$"" + Environment.NewLine
);
}
catch (Exception ex)
{
//
// Logging Request Error ...
stopwatch.Stop();
logger.LogError(ex,
"Request failed: {Method} {Path} after {Elapsed}ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds
);
//
// Throw Exception Agains for Handling using Top Level Middlewares ...
throw;
}
}
}
}
+5 -2
View File
@@ -9,8 +9,8 @@ using System.Threading.Tasks;
using xLoggingService.Models; using xLoggingService.Models;
using xCommons.Configurations; using xCommons.Configurations;
using xLoggingService.Interfaces; using xLoggingService.Interfaces;
using xLoggingService.Configuration;
using xLoggingService.Extensions; using xLoggingService.Extensions;
using xLoggingService.Configuration;
namespace xLoggingService.Writers namespace xLoggingService.Writers
{ {
@@ -62,7 +62,10 @@ namespace xLoggingService.Writers
} }
// //
var path = Path.Combine(configuration.File.Directory, configuration.File.FileName.Replace("-", "-")); string date = DateTime.UtcNow.ToString("yyyy-MM-dd");
var path = Path.Combine(
configuration.File.Directory,
configuration.File.FileName.Replace("-", $"-{date}"));
// //
lock (sync) lock (sync)
+7 -4
View File
@@ -19,8 +19,7 @@
<!-- Icon Handling --> <!-- Icon Handling -->
<ItemGroup> <ItemGroup>
<None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true" <None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
PackagePath="\icon.png" />
</ItemGroup> </ItemGroup>
<!-- Local Modules --> <!-- Local Modules -->
@@ -34,9 +33,13 @@
<!-- Dependencies --> <!-- Dependencies -->
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.6.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.6.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.6.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="5.0.0" /> <PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.6.0" />
</ItemGroup> </ItemGroup>
<!-- For XML Documentation Support --> <!-- For XML Documentation Support -->