naps2/NAPS2.Lib/NLogConfig.cs

56 lines
2.0 KiB
C#
Raw Normal View History

using System.Text;
using NLog;
2022-08-21 03:50:38 +03:00
using NLog.Config;
using NLog.Extensions.Logging;
2023-04-22 08:38:49 +03:00
using NLog.Filters;
using NLog.LayoutRenderers;
2022-08-21 03:50:38 +03:00
using NLog.Targets;
using ILogger = Microsoft.Extensions.Logging.ILogger;
2022-08-21 03:50:38 +03:00
namespace NAPS2;
public static class NLogConfig
2022-08-21 03:50:38 +03:00
{
2023-04-22 08:38:49 +03:00
public static ILogger CreateLogger(Func<bool> enableDebugLogging)
2022-08-21 03:50:38 +03:00
{
2023-11-26 00:47:17 +03:00
LogManager.Setup().SetupExtensions(ext =>
{
ext.RegisterLayoutRenderer<CustomExceptionLayoutRenderer>("exception");
});
2022-08-21 03:50:38 +03:00
var config = new LoggingConfiguration();
var target = new FileTarget
{
FileName = Path.Combine(Paths.AppData, "errorlog.txt"),
Layout = "${longdate} ${processid} ${message} ${exception:format=tostring}",
ArchiveAboveSize = 100000,
2023-12-21 17:17:31 +03:00
MaxArchiveFiles = 1,
2023-11-23 20:06:28 +03:00
ConcurrentWrites = true
2022-08-21 03:50:38 +03:00
};
var debugTarget = new FileTarget
{
FileName = Path.Combine(Paths.AppData, "debuglog.txt"),
Layout = "${longdate} ${processid} ${message} ${exception:format=tostring}",
ArchiveAboveSize = 100000,
2023-11-23 20:06:28 +03:00
MaxArchiveFiles = 1,
ConcurrentWrites = true
};
2022-08-21 03:50:38 +03:00
config.AddTarget("errorlogfile", target);
config.AddTarget("debuglogfile", debugTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));
var debugRule = new LoggingRule("*", LogLevel.Trace, debugTarget);
2023-04-22 08:38:49 +03:00
debugRule.Filters.Add(new WhenMethodFilter(_ => enableDebugLogging() ? FilterResult.Log : FilterResult.Ignore));
config.LoggingRules.Add(debugRule);
2022-08-21 03:50:38 +03:00
LogManager.Configuration = config;
return new NLogLoggerFactory().CreateLogger("NAPS2");
2022-08-21 03:50:38 +03:00
}
private class CustomExceptionLayoutRenderer : ExceptionLayoutRenderer
{
protected override void AppendToString(StringBuilder sb, Exception ex)
{
2023-04-04 10:23:26 +03:00
// Note we don't want to use the AppendDemystified() helper
// https://github.com/benaadams/Ben.Demystifier/issues/85
sb.Append(ex.Demystify());
}
}
2022-08-21 03:50:38 +03:00
}