เพิ่ม middleware ในการเขียน log โดยเขียนไป elasticsearch โดยไม่ใช้ Serilog เพื่อจัด format เอง

This commit is contained in:
Suphonchai Phoonsawat 2025-03-21 15:44:11 +07:00
parent 71a1c48392
commit b8fef58b28
6 changed files with 130 additions and 10 deletions

View file

@ -10,6 +10,8 @@
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="7.0.9" />
<PackageReference Include="NEST" Version="7.17.5" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="ThaiBahtText" Version="1.0.103" />
</ItemGroup>

View file

@ -0,0 +1,101 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using Nest;
using Serilog;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
namespace BMA.EHR.Domain.Middlewares
{
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var settings = new ConnectionSettings(new Uri("http://192.168.1.40:9200"))
.DefaultIndex("bma-ehr-log-test-net");
var client = new ElasticClient(settings);
var startTime = DateTime.UtcNow;
var stopwatch = Stopwatch.StartNew();
string requestBody = await ReadRequestBodyAsync(context);
var originalBodyStream = context.Response.Body;
using (var memoryStream = new MemoryStream())
{
// เปลี่ยน stream ของ Response เพื่อให้สามารถอ่านได้
context.Response.Body = memoryStream;
await _next(context); // ดำเนินการต่อไปยัง Middleware อื่น ๆ
stopwatch.Stop();
var processTime = stopwatch.ElapsedMilliseconds;
var endTime = DateTime.UtcNow;
var logType = context.Response.StatusCode switch
{
>= 500 => "error",
>= 400 => "warning",
_ => "info"
};
// อ่านข้อมูลจาก Response หลังจากที่ได้ถูกส่งออกไป
memoryStream.Seek(0, SeekOrigin.Begin);
var responseBody = new StreamReader(memoryStream).ReadToEnd();
var logData = new
{
logType = logType,
ip = context.Connection.RemoteIpAddress?.ToString(),
rootId = context.Items["RootId"] ?? null,
systemName = "test",
startTimeStamp = startTime.ToString("o"),
endTimeStamp = endTime.ToString("o"),
processTime = processTime,
host = context.Request.Host.Value,
method = context.Request.Method,
endpoint = context.Request.Path + context.Request.QueryString,
responseCode = context.Response.StatusCode == 304 ? "200" : context.Response.StatusCode.ToString(),
responseDescription = context.Items["ResponseMessage"] ?? null,
input = requestBody,
output = responseBody
};
// เขียนข้อมูลกลับไปยัง original Response body
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(originalBodyStream);
client.IndexDocument(logData);
}
//Log.Information("API Request Log: {@LogData}", logData);
}
private async Task<string> ReadRequestBodyAsync(HttpContext context)
{
context.Request.EnableBuffering();
using var reader = new StreamReader(context.Request.Body, leaveOpen: true);
var body = await reader.ReadToEndAsync();
context.Request.Body.Position = 0;
return body;
}
}
}

View file

@ -174,6 +174,7 @@ var app = builder.Build();
app.UseStaticFiles();
app.MapControllers();
app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
{
Authorization = new[] { new CustomAuthorizeFilter() }
@ -223,7 +224,8 @@ ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot configuration,
return new ElasticsearchSinkOptions(new Uri(configuration["ElasticConfiguration:Uri"] ?? ""))
{
AutoRegisterTemplate = true,
IndexFormat = $"{Assembly.GetExecutingAssembly()?.GetName()?.Name?.ToLower().Replace(".", "-")}-{environment?.ToLower().Replace(".", "-")}"
IndexFormat = "bma-ehr-log-index",
//IndexFormat = $"{Assembly.GetExecutingAssembly()?.GetName()?.Name?.ToLower().Replace(".", "-")}-{environment?.ToLower().Replace(".", "-")}"
};
}

View file

@ -9,8 +9,9 @@
}
},
"ElasticConfiguration": {
"Uri": "http://localhost:9200"
"Uri": "http://192.168.1.40:9200"
},
"LogIndex": "bma-ehr-log-index",
"AllowedHosts": "*",
"ConnectionStrings": {
//"DefaultConnection": "User Id=sys;Password=P@ssw0rd;DBA Privilege=SYSDBA;Data Source=localhost:1521/ORCLCDB",

View file

@ -40,6 +40,7 @@
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="8.0.8" />
<PackageReference Include="Microsoft.IdentityModel.Logging" Version="6.31.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="NEST" Version="7.17.5" />
<PackageReference Include="runtime.osx.10.10-x64.CoreCompat.System.Drawing" Version="6.0.5.128" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />

View file

@ -161,6 +161,7 @@ app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();
app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
@ -196,14 +197,25 @@ void ConfigureLogs()
.Build();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Error()
.WriteTo.Console()
.Enrich.WithExceptionDetails()
.WriteTo.Elasticsearch(ConfigureElasticSink(configuration, environment ?? ""))
.Enrich.WithProperty("Environment", environment)
.ReadFrom.Configuration(configuration)
.CreateLogger();
.WriteTo.Console() // แสดง Log บน Console
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://192.168.1.40:9200"))
{
AutoRegisterTemplate = true,
IndexFormat = "bma-ehr-log-test" // เก็บเป็น daily index
})
.CreateLogger();
Log.Information("Test Log to Elasticsearch");
//Log.Logger = new LoggerConfiguration()
// .Enrich.FromLogContext()
// .MinimumLevel.Error()
// .WriteTo.Console()
// .Enrich.WithExceptionDetails()
// .WriteTo.Elasticsearch(ConfigureElasticSink(configuration, environment ?? ""))
// .Enrich.WithProperty("Environment", environment)
// .ReadFrom.Configuration(configuration)
// .CreateLogger();
}
ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot configuration, string environment)
@ -211,6 +223,7 @@ ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot configuration,
return new ElasticsearchSinkOptions(new Uri(configuration["ElasticConfiguration:Uri"] ?? ""))
{
AutoRegisterTemplate = true,
//IndexFormat = "bma-ehr-log-index-netS",
IndexFormat = $"{Assembly.GetExecutingAssembly()?.GetName()?.Name?.ToLower().Replace(".", "-")}-{environment?.ToLower().Replace(".", "-")}"
};
}