Integrate NLog for centralized logging, replacing Console calls across CLI tasks. Add LoggingService helper for setup and logger retrieval. Update project dependencies.
This commit is contained in:
56
Cli/Helper/LoggingService.cs
Normal file
56
Cli/Helper/LoggingService.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using NLog;
|
||||
using NLog.Config;
|
||||
using NLog.Targets;
|
||||
|
||||
namespace FsToolbox.Cli.Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// Central logging setup using NLog with console and file targets.
|
||||
/// </summary>
|
||||
public static class LoggingService
|
||||
{
|
||||
private static bool _initialized;
|
||||
|
||||
/// <summary>
|
||||
/// Configures NLog with console and rolling file targets.
|
||||
/// </summary>
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_initialized) return;
|
||||
|
||||
var config = new LoggingConfiguration();
|
||||
var layout = "${longdate} | ${uppercase:${level}} | ${logger} | ${message}${onexception:inner=${newline}${exception:format=tostring}}";
|
||||
|
||||
var consoleTarget = new ConsoleTarget("console")
|
||||
{
|
||||
Layout = layout
|
||||
};
|
||||
|
||||
var fileTarget = new FileTarget("file")
|
||||
{
|
||||
FileName = "${basedir}/logs/fstool.log",
|
||||
ArchiveEvery = FileArchivePeriod.Day,
|
||||
ArchiveNumbering = ArchiveNumberingMode.Rolling,
|
||||
MaxArchiveFiles = 7,
|
||||
Layout = layout,
|
||||
CreateDirs = true
|
||||
};
|
||||
|
||||
config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);
|
||||
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget);
|
||||
|
||||
LogManager.Configuration = config;
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a logger for the specified type.
|
||||
/// </summary>
|
||||
public static Logger GetLogger<T>() => LogManager.GetLogger(typeof(T).FullName);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a logger for the specified name.
|
||||
/// </summary>
|
||||
public static Logger GetLogger(string name) => LogManager.GetLogger(name);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user