using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NTP.Application.Abstractions; using Oracle.ManagedDataAccess.Client; namespace NTP.Infrastructure.Persistence; /// /// Inserts into NTP.SYSTEM_ERRORS (ID from SEQ_SYSTEM_ERRORS, ERROR, ERRORDATE, IPADDRESS(15), USERID(50), BROWSER(200)). /// Uses its own short-lived connection so it still works when the request's connection / transaction is the thing that failed, /// and swallows every failure (logging an error must never hide the original one). /// internal sealed class SystemErrorLogger(IOptions options, ILogger logger) : ISystemErrorLogger { public async Task LogAsync(Exception exception, string? userId, string? ipAddress, string? browser, string? requestInfo) { try { var cs = options.Value.ConnectionString; if (string.IsNullOrWhiteSpace(cs)) return; await using var con = new OracleConnection(cs); await con.OpenAsync(CancellationToken.None); await using var cmd = con.CreateCommand(); cmd.BindByName = true; cmd.CommandText = """ INSERT INTO SYSTEM_ERRORS (ID, ERROR, ERRORDATE, IPADDRESS, USERID, BROWSER) VALUES (SEQ_SYSTEM_ERRORS.NEXTVAL, :Err, SYSDATE, :Ip, :UserId, :Browser) """; cmd.Parameters.Add(new OracleParameter("Err", OracleDbType.Clob) { Value = Describe(exception, requestInfo) }); cmd.Parameters.Add(new OracleParameter("Ip", OracleDbType.Varchar2) { Value = Cut(ipAddress, 15) ?? "-" }); cmd.Parameters.Add(new OracleParameter("UserId", OracleDbType.Varchar2) { Value = Cut(userId, 50) }); cmd.Parameters.Add(new OracleParameter("Browser", OracleDbType.Varchar2) { Value = Cut(browser, 200) }); await cmd.ExecuteNonQueryAsync(CancellationToken.None); } catch (Exception ex) { logger.LogWarning(ex, "Could not save the error into SYSTEM_ERRORS"); } } private static string? Cut(string? v, int max) => string.IsNullOrEmpty(v) ? null : v.Length <= max ? v : v[..max]; /// Same layout as the legacy log: details, message, SQL (n/a), then where it happened. private static string Describe(Exception ex, string? requestInfo) { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(requestInfo)) sb.AppendLine("Request: " + requestInfo); for (var e = ex; e is not null; e = e.InnerException!) { sb.AppendLine($"MSG: {e.GetType().FullName}: {e.Message}"); if (e is OracleException ora) sb.AppendLine($"ORA-{ora.Number:D5}"); if (e.InnerException is null) break; } sb.AppendLine("Details:"); sb.AppendLine(ex.ToString()); return sb.ToString(); } }