我正在构建一个dotnet核心应用程序,我需要从日志中编辑社会安全号码。目前,该应用程序正在使用控制台记录器。这是最好的做法吗?本质上,我想为控制台记录器创建一个适配器,它拦截日志消息,编辑社会安全号码,并将其发送到控制台记录器。类似下面的代码。
public class LogRedactor : ILogger
{
private static readonly Regex SsnRegex = new Regex("<SSN>(.*)</SSN>", RegexOptions.Compiled);
private readonly ILogger _logger;
public LogRedactor(ILogger logger)
{
_logger = logger;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
if (state is FormattedLogValues)
_logger.Log(logLevel, eventId, state, exception,
(o, e) => SsnRegex.Replace(o.ToString(), "<SSN>REDACTED</SSN>"));
else
_logger.Log(logLevel, eventId, state, exception, formatter);
}
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(logLevel);
}
public IDisposable BeginScope<TState>(TState state)
{
return _logger.BeginScope(state);
}
}
public class RedactedConsoleLoggingProvider : ILoggerProvider
{
private readonly ConsoleLoggerProvider _consoleLogger;
public RedactedConsoleLoggingProvider(ConsoleLoggerProvider consoleLogger)
{
_consoleLogger = consoleLogger;
}
public void Dispose()
{
_consoleLogger.Dispose();
}
public ILogger CreateLogger(string categoryName)
{
var logger = _consoleLogger.CreateLogger(categoryName);
return new LogRedactor(logger);
}
}
我上面所说的“有效”,但我担心它很脆弱而且不完整。任何方向都非常感谢。