Initial Commit after switching from SVN to git
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace fds.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Writes log entries to Debug output and a rolling file.
|
||||
/// Database logging is wired up but disabled — set <see cref="DatabaseLoggingEnabled"/> to true to activate.
|
||||
/// </summary>
|
||||
public sealed class FdsLoggerProvider : ILoggerProvider
|
||||
{
|
||||
private readonly string _logDirectory;
|
||||
|
||||
/// <summary>Set to true to activate database logging via fds__admin_logdebug.</summary>
|
||||
public static bool DatabaseLoggingEnabled { get; set; } = false;
|
||||
|
||||
public FdsLoggerProvider(string? logDirectory = null)
|
||||
{
|
||||
_logDirectory = logDirectory
|
||||
?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp");
|
||||
Directory.CreateDirectory(_logDirectory);
|
||||
}
|
||||
|
||||
public ILogger CreateLogger(string categoryName) =>
|
||||
new FdsLogger(categoryName, _logDirectory);
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
internal sealed class FdsLogger : ILogger
|
||||
{
|
||||
private readonly string _categoryName;
|
||||
private readonly string _logDirectory;
|
||||
private static readonly Lock _fileLock = new();
|
||||
|
||||
internal FdsLogger(string categoryName, string logDirectory)
|
||||
{
|
||||
_categoryName = categoryName;
|
||||
_logDirectory = logDirectory;
|
||||
}
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
|
||||
Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
|
||||
string message = formatter(state, exception);
|
||||
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
string levelTag = logLevel switch
|
||||
{
|
||||
LogLevel.Trace => "TRC",
|
||||
LogLevel.Debug => "DBG",
|
||||
LogLevel.Information => "INF",
|
||||
LogLevel.Warning => "WRN",
|
||||
LogLevel.Error => "ERR",
|
||||
LogLevel.Critical => "CRT",
|
||||
_ => "???"
|
||||
};
|
||||
|
||||
string line = $"{timestamp} [{levelTag}] {_categoryName}: {message}";
|
||||
if (exception != null)
|
||||
line += $"\r\n Exception: {exception.Message}\r\n Stack: {exception.StackTrace}";
|
||||
|
||||
// Always emit to Debug output
|
||||
Debug.WriteLine(line);
|
||||
|
||||
// Always write to file
|
||||
string filename = logLevel >= LogLevel.Error ? "ErrorLog.txt" : "DebugLog.txt";
|
||||
AppendToFile(filename, line);
|
||||
|
||||
// Database logging — prepared, not activated
|
||||
if (FdsLoggerProvider.DatabaseLoggingEnabled)
|
||||
WriteToDatabase(_categoryName, message, exception);
|
||||
}
|
||||
|
||||
private void AppendToFile(string filename, string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_fileLock)
|
||||
File.AppendAllText(Path.Combine(_logDirectory, filename), line + "\r\n");
|
||||
}
|
||||
catch { /* never throw from logger */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepared DB logging via fds__admin_logdebug.
|
||||
/// Enable by setting <see cref="FdsLoggerProvider.DatabaseLoggingEnabled"/> = true.
|
||||
/// </summary>
|
||||
private static void WriteToDatabase(string codeReference, string message, Exception? exception)
|
||||
{
|
||||
// Activate by setting FdsLoggerProvider.DatabaseLoggingEnabled = true in appsettings / startup.
|
||||
//
|
||||
// using var con = new Microsoft.Data.SqlClient.SqlConnection(FdsConfig.FDSConnectionString());
|
||||
// using var cmd = new Microsoft.Data.SqlClient.SqlCommand(
|
||||
// "EXECUTE [dbo].[fds__admin_logdebug] @CodeReference, @ExceptionMessage, @StackTrace, @Data;", con);
|
||||
// cmd.Parameters.AddWithValue("@CodeReference", codeReference);
|
||||
// cmd.Parameters.AddWithValue("@ExceptionMessage", (object?)exception?.Message ?? DBNull.Value);
|
||||
// cmd.Parameters.AddWithValue("@StackTrace", (object?)exception?.StackTrace ?? DBNull.Value);
|
||||
// cmd.Parameters.AddWithValue("@Data", message);
|
||||
// con.Open();
|
||||
// cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
public static class FdsLoggingExtensions
|
||||
{
|
||||
public static ILoggingBuilder AddFdsLogging(this ILoggingBuilder builder, string? logDirectory = null)
|
||||
{
|
||||
builder.AddProvider(new FdsLoggerProvider(logDirectory));
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user