77 lines
2.3 KiB
C#
77 lines
2.3 KiB
C#
namespace ApiOPE.Services;
|
|
|
|
public sealed class OpeRequestFileLogger
|
|
{
|
|
private readonly string _path;
|
|
private readonly ILogger<OpeRequestFileLogger> _logger;
|
|
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
|
|
|
public OpeRequestFileLogger(
|
|
IWebHostEnvironment environment,
|
|
IConfiguration configuration,
|
|
ILogger<OpeRequestFileLogger> logger)
|
|
{
|
|
_logger = logger;
|
|
var configuredPath = configuration["Ope:RequestLogPath"];
|
|
_path = string.IsNullOrWhiteSpace(configuredPath)
|
|
? Path.Combine(environment.ContentRootPath, "logs", "ope-requests.jsonl")
|
|
: configuredPath;
|
|
}
|
|
|
|
public async Task WriteAsync(OpeRequestLogEntry entry, CancellationToken cancellationToken = default)
|
|
{
|
|
try
|
|
{
|
|
var directory = Path.GetDirectoryName(_path);
|
|
if (!string.IsNullOrWhiteSpace(directory))
|
|
{
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
var line = entry.ToDisplayLine() + Environment.NewLine;
|
|
await _writeLock.WaitAsync(cancellationToken);
|
|
try
|
|
{
|
|
await File.AppendAllTextAsync(_path, line, cancellationToken);
|
|
}
|
|
finally
|
|
{
|
|
_writeLock.Release();
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
// El registro de diagnóstico nunca debe impedir una llamada OPE.
|
|
_logger.LogWarning(
|
|
exception,
|
|
"No se pudo escribir el registro de peticiones OPE en {Path}.",
|
|
_path);
|
|
}
|
|
}
|
|
}
|
|
|
|
public sealed record OpeRequestLogEntry(
|
|
DateTimeOffset TimestampUtc,
|
|
string Method,
|
|
string Path,
|
|
int StatusCode,
|
|
string Result,
|
|
string? TransactionId,
|
|
string? RequestId,
|
|
string? ClientTokenFingerprint,
|
|
string? FailureReason)
|
|
{
|
|
public string ToDisplayLine()
|
|
=> string.Join(
|
|
" | ",
|
|
TimestampUtc.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss zzz"),
|
|
Method,
|
|
Path,
|
|
$"HTTP {StatusCode}",
|
|
Result,
|
|
$"transaccion={TransactionId ?? "-"}",
|
|
$"peticion={RequestId ?? "-"}",
|
|
$"cliente={ClientTokenFingerprint ?? "-"}",
|
|
$"motivo={FailureReason ?? "-"}");
|
|
}
|