static Logger() { var config = new NLog.Config.LoggingConfiguration(); var fileLog = new FileTarget("logfile") { FileName = "WTFTwitch.log" }; fileLog.Layout = DefaultLayout; var consoleLog = new ColoredConsoleTarget("consolelog"); consoleLog.Layout = DefaultLayout; foreach (var rule in GetColorRules()) { consoleLog.RowHighlightingRules.Add(rule); } config.AddRuleForAllLevels(fileLog); config.AddRuleForAllLevels(consoleLog); NLog.LogManager.Configuration = config; _logInstance = NLog.LogManager.GetCurrentClassLogger(); }
private void ConfigureLogger() { var Config = new NLog.Config.LoggingConfiguration(); var LogConsole = new NLog.Targets.ConsoleTarget("LogConsole"); var FileTarget = new NLog.Targets.FileTarget("File") { FileName = "${basedir}/file.txt", Layout = "${message}" }; Config.AddRuleForAllLevels(LogConsole); Config.AddRuleForAllLevels(FileTarget); NLog.LogManager.Configuration = Config; }
private static void Main(string[] args) { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = GlobalPaths.ConfigDir + "\\Launcher-log-" + DateTime.Today.ToString("MM-dd-yyyy") + ".log" }; config.AddRuleForAllLevels(logfile); LogManager.Configuration = config; GlobalFuncs.ReadInfoFile(GlobalPaths.ConfigDir + "\\" + GlobalPaths.InfoName); GlobalFuncs.Config(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigName, false); GlobalVars.ColorsLoaded = GlobalFuncs.InitColors(); if (args.Length == 0) { RunLauncher(); } else { CommandLineArguments.Arguments CommandLine = new CommandLineArguments.Arguments(args); if (CommandLine["sdk"] != null) { System.Windows.Forms.Application.Run(new NovetusSDK()); } } }
private Logger SetupNLog() { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("piosk-push-client") { FileName = "./piosk-push-client.log", ArchiveAboveSize = this.config.MaxLogFileSizeBytes, MaxArchiveFiles = 3 }; config.AddRuleForAllLevels(logfile); NLog.LogManager.Configuration = config; // NLog is our way to learn about application crashes as well var logger = LogManager.GetCurrentClassLogger(); AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs eArg) => { logger.Error(eArg.ExceptionObject?.ToString()); LogManager.Flush(); LogManager.Shutdown(); }; return(logger); }
public static Microsoft.Extensions.Logging.ILogger CreateILoggerFromNLog(bool debug = false) { // NLog build Example for microsoft ILogger find on : // https://stackoverflow.com/questions/56534730/nlog-works-in-asp-net-core-app-but-not-in-net-core-xunit-test-project var configuration = new NLog.Config.LoggingConfiguration(); configuration.AddRuleForAllLevels(new NLog.Targets.ConsoleTarget()); NLog.Web.NLogBuilder.ConfigureNLog(configuration); // Create provider to bridge Microsoft.Extensions.Logging var provider = new NLog.Extensions.Logging.NLogLoggerProvider(); // Create logger Microsoft.Extensions.Logging.ILogger logger = provider.CreateLogger(typeof(DnsSrvToolsIntergrationTest).FullName); if (debug) { logger.LogDebug("This is a test of the log system : LogDebug."); logger.LogTrace("This is a test of the log system : LogTrace."); logger.LogInformation("This is a test of the log system : LogInformation."); logger.LogWarning("This is a test of the log system : LogWarning."); logger.LogError("This is a test of the log system : LogError."); logger.LogCritical("This is a test of the log system : LogCritical."); } return(logger); }
public async Task Should_log_nsb_logs() { var config = new NLog.Config.LoggingConfiguration(); var memoryTarget = new NLog.Targets.MemoryTarget(); config.AddRuleForAllLevels(memoryTarget); LogManager.Configuration = config; NsbLogManager.UseFactory(new ExtensionsLoggerFactory(new NLogLoggerFactory())); var endpointConfiguration = new EndpointConfiguration("LoggingTests"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UsePersistence <LearningPersistence>(); var endpoint = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Assert.IsNotEmpty(memoryTarget.Logs); } finally { await endpoint.Stop() .ConfigureAwait(false); } }
private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = GlobalPaths.ConfigDir + "\\URI-log-" + DateTime.Today.ToString("MM-dd-yyyy") + ".log" }; config.AddRuleForAllLevels(logfile); LogManager.Configuration = config; GlobalFuncs.ReadInfoFile(GlobalPaths.ConfigDir + "\\" + GlobalPaths.InfoName); GlobalFuncs.Config(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigName, false); GlobalVars.ColorsLoaded = GlobalFuncs.InitColors(); if (args.Length == 0) { Application.Run(new InstallForm()); } else { foreach (string s in args) { LocalVars.SharedArgs = s; } Application.Run(new LoaderForm()); } }
public void ContextPropertiesILoggerTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); var target = new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }; target.ContextProperties.Add(new Targets.TargetPropertyWithContext() { Name = "ThreadId", Layout = "${threadid}" }); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello {Planet}", "Earth"); Assert.Equal("Hello \"Earth\"", ilogger.LastLogMessage); Assert.Equal(3, ilogger.LastLogProperties.Count); Assert.Equal("Planet", ilogger.LastLogProperties[0].Key); Assert.Equal("Earth", ilogger.LastLogProperties[0].Value); Assert.Equal("ThreadId", ilogger.LastLogProperties[1].Key); Assert.Equal(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), ilogger.LastLogProperties[1].Value); Assert.Equal("Hello {Planet}", ilogger.LastLogProperties[2].Value); }
public static void Main(string[] args) { _handler += new EventHandler(CloseHandler); SetConsoleCtrlHandler(_handler, true); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = GlobalPaths.ConfigDir + "\\CMD-log-" + DateTime.Today.ToString("MM-dd-yyyy") + ".log" }; config.AddRuleForAllLevels(logfile); LogManager.Configuration = config; LoadCMDArgs(args); if (!LocalVars.PrintHelp) { GlobalFuncs.ReadInfoFile(GlobalPaths.ConfigDir + "\\" + GlobalPaths.InfoName, true, GlobalPaths.RootPathLauncher + "\\Novetus.exe"); GlobalFuncs.TurnOffInitialSequence(); Console.Title = "Novetus " + GlobalVars.ProgramInformation.Version + " CMD"; GlobalFuncs.ConsolePrint("NovetusCMD version " + GlobalVars.ProgramInformation.Version + " loaded.", 1); GlobalFuncs.ConsolePrint("Novetus path: " + GlobalPaths.BasePath, 1); GlobalFuncs.ConsolePrint("NovetusCMD is now loading main server configurations from the INI file.", 5); if (!File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigName)) { GlobalFuncs.ConsolePrint("WARNING 2 - " + GlobalPaths.ConfigName + " not found. Creating one with default values.", 5); WriteConfigValues(); } ReadConfigValues(true); LoadOverrideINIArgs(args); InitUPnP(); GlobalFuncs.ConsolePrint("Launching a " + GlobalVars.UserConfiguration.SelectedClient + " server on " + GlobalVars.UserConfiguration.Map + " with " + GlobalVars.UserConfiguration.PlayerLimit + " players.", 1); switch (LocalVars.DebugMode) { case true: GlobalFuncs.CreateTXT(); break; case false: default: StartServer(LocalVars.StartInNo3D); break; } } else { LocalFuncs.CommandInfo(); } Console.ReadKey(); }
static CustomLogger() { var config = new NLog.Config.LoggingConfiguration(); var consoleLogger = CreateConsoleTarget(); config.AddTarget(consoleLogger); config.AddRuleForAllLevels(consoleLogger); LogManager.Configuration = config; LogManager.Configuration.Variables["mbbsdir"] = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; }
/// <summary> /// 配置Logger /// </summary> static Logger() { var config = new NLog.Config.LoggingConfiguration(); string layout = LoggerConfig.Layout; //控制台 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.Console)) { AddTarget(new NLog.Targets.ColoredConsoleTarget { Name = LoggerConfig.LoggerName, Layout = layout }); } //文件 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.File)) { AddTarget(new NLog.Targets.FileTarget { Name = LoggerConfig.LoggerName, Layout = layout, FileName = Path.Combine(Directory.GetCurrentDirectory(), "logs", "${date:format=yyyy-MM-dd}.txt"), Encoding = Encoding.UTF8 }); } //数据库 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.RDBMS)) { AddTarget(new RDBMSTarget { Layout = layout }); } //ElasticSearch if (GlobalSwitch.LoggerType.HasFlag(LoggerType.ElasticSearch)) { AddTarget(new ElasticSearchTarget { Layout = layout }); } NLog.LogManager.Configuration = config; void AddTarget(NLog.Targets.Target target) { config.AddTarget(target); config.AddRuleForAllLevels(target); } }
/// <summary> /// 配置Logger /// </summary> static Logger() { var config = new NLog.Config.LoggingConfiguration(); string layout = LoggerConfig.Layout; //控制台 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.Console)) { AddTarget(new NLog.Targets.ColoredConsoleTarget { Name = LoggerConfig.LoggerName, Layout = layout }); } //文件 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.File)) { AddTarget(new NLog.Targets.FileTarget { Name = LoggerConfig.LoggerName, Layout = layout, FileName = $"${{basedir}}/A_logs/{DateTime.Now.ToString("yyyy-MM")}/{DateTime.Now.ToString("yyyy-MM-dd")}.txt" }); } //数据库 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.RDBMS)) { AddTarget(new RDBMSTarget { Layout = layout }); } //ElasticSearch if (GlobalSwitch.LoggerType.HasFlag(LoggerType.ElasticSearch)) { AddTarget(new ElasticSearchTarget { Layout = layout }); } NLog.LogManager.Configuration = config; void AddTarget(NLog.Targets.Target target) { config.AddTarget(target); config.AddRuleForAllLevels(target); } }
public static void Configure() { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = MyConfiguration.LOG_FILE, Layout = @"${date:format=HH\:mm\:ss} ${level} ${logger} ${message} ${exception}" }; config.AddRuleForAllLevels(logfile); NLog.LogManager.Configuration = config; }
public static void Config() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt", Layout = "${longdate} ${uppercase:${level}} ${message} ${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}", }; var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole") { Layout = "${longdate} ${uppercase:${level}} ${message} ${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}", }; // Rules for mapping loggers to targets config.AddRuleForAllLevels(logconsole); config.AddRuleForAllLevels(logfile); // Apply config LogManager.Configuration = config; }
static CustomLogger() { var config = new NLog.Config.LoggingConfiguration(); //Setup Console Logging var consoleLogger = new ColoredConsoleTarget("consoleLogger") { Layout = Layout.FromString("${shortdate} ${time} ${level} ${callsite} ${message}"), UseDefaultRowHighlightingRules = true }; consoleLogger.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Debug"), ForegroundColor = ConsoleOutputColor.Gray }); consoleLogger.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Info"), ForegroundColor = ConsoleOutputColor.White }); consoleLogger.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Warn"), ForegroundColor = ConsoleOutputColor.DarkYellow }); consoleLogger.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Error"), ForegroundColor = ConsoleOutputColor.Red }); config.AddTarget(consoleLogger); var fileLogger = new FileTarget("fileLogger") { FileName = @"c:\dos\log\log.txt", Layout = Layout.FromString("${shortdate} ${time} ${level} ${callsite} ${message}"), DeleteOldFileOnStartup = true }; //config.AddTarget(fileLogger); config.AddRuleForAllLevels(consoleLogger); //config.AddRuleForAllLevels(fileLogger); LogManager.Configuration = config; }
static CustomLogger() { var config = new NLog.Config.LoggingConfiguration(); //Setup Console Logging var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = Layout.FromString("${shortdate}\t${time}\t${level}\t${callsite}\t${message}") }; config.AddTarget(logconsole); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = @"c:\nes\log.txt", Layout = Layout.FromString("${shortdate}\t${time}\t${level}\t${callsite}\t${message}"), DeleteOldFileOnStartup = true }; config.AddTarget(logfile); config.AddRuleForAllLevels(logconsole); config.AddRuleForAllLevels(logfile); LogManager.Configuration = config; }
static CustomLogger() { var config = new NLog.Config.LoggingConfiguration(); //Setup Console Logging var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = Layout.FromString("${shortdate}\t${time}\t${message}") }; config.AddTarget(logconsole); config.AddRuleForAllLevels(logconsole); LogManager.Configuration = config; }
public void FilterILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Debug("Hello World"); Assert.Null(ilogger.LastLogMessage); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = LocalPaths.FixedConfigDir + "\\Bootstrapper-log-" + DateTime.Today.ToString("MM-dd-yyyy") + ".log" }; config.AddRuleForAllLevels(logfile); LogManager.Configuration = config; Application.Run(new NovetusLaunchForm()); }
public void EventQueueGrow_OnQueueGrow() { int queueLimit = 2; int loggedEventCount = 10; int expectedGrowingNumber = 0; #if NETCOREAPP2_0 expectedGrowingNumber = loggedEventCount - queueLimit; #else expectedGrowingNumber = 3; #endif int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapperForEventTests() { WrappedTarget = myTarget, QueueLimit = queueLimit, TimeToSleepBetweenBatches = 500, // Make it slow OverflowAction = AsyncTargetWrapperOverflowAction.Grow, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.EventQueueGrow += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(expectedGrowingNumber, eventsCounter); } finally { logFactory.Configuration = null; } }
public void SimpleILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello World"); Assert.Equal("Hello World", ilogger.LastLogMessage); Assert.Single(ilogger.LastLogProperties); Assert.Equal("Hello World", ilogger.LastLogProperties[0].Value); }
public void Test(NLogLogLevel logLevel, Enyim.LogLevel enyimLevel, string message, Exception exception) { var mock = new Moq.Mock <NLog.Targets.TargetWithContext>(MockBehavior.Loose) { CallBase = true }; var config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(mock.Object); LogManager.AssignFactory(new Enyim.Diagnostics.NLogLoggerFactory(new NLog.LogFactory(config))); LogManager.Create(typeof(NLogAdapterTests)).Log(enyimLevel, exception, message); mock.Protected().Verify("Write", Times.Once(), ItExpr.Is <LogEventInfo>(info => info.Level == logLevel && info.Message == message && info.Exception == exception)); }
private void EnqueuQueueBlock_OnClose_ReleasesWriters(bool forceLockingQueue) { // Setup var slowTarget = new MethodCallTarget("slowTarget", (logEvent, parms) => System.Threading.Thread.Sleep(300)); var targetWrapper = new AsyncTargetWrapper("asynSlowTarget", slowTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Block, QueueLimit = 3, ForceLockingQueue = forceLockingQueue, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); // Act long allTasksCompleted = 0; AsyncHelpers.ForEachItemInParallel(System.Linq.Enumerable.Range(1, 6), (ex) => Interlocked.Exchange(ref allTasksCompleted, 1), (value, cont) => { for (int i = 0; i < 100; ++i) { logger.Info("Hello {0}", value); } cont(null); }); Thread.Sleep(150); // Let them get stuck Assert.Equal(0, Interlocked.Read(ref allTasksCompleted)); targetWrapper.Close(); // Release those who are stuck, and discard the rest // Assert for (int i = 0; i < 100; i++) { if (Interlocked.Read(ref allTasksCompleted) == 1) { break; } Thread.Sleep(10); } Assert.Equal(1, Interlocked.Read(ref allTasksCompleted)); }
static CustomLogger() { var config = new NLog.Config.LoggingConfiguration(); var consoleLogger = CreateConsoleTarget(); config.AddTarget(consoleLogger); var fileLogger = new FileTarget("fileLogger") { FileName = @"c:\dos\log\log.txt", Layout = Layout.FromString("${shortdate} ${time} ${level} ${callsite} ${message}"), DeleteOldFileOnStartup = true }; //config.AddTarget(fileLogger); config.AddRuleForAllLevels(consoleLogger); //config.AddRuleForAllLevels(fileLogger); LogManager.Configuration = config; }
public void StructuredILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello {Planet}", "Earth"); Assert.Equal("Hello \"Earth\"", ilogger.LastLogMessage); Assert.Equal(2, ilogger.LastLogProperties.Count); Assert.Equal("Planet", ilogger.LastLogProperties[0].Key); Assert.Equal("Earth", ilogger.LastLogProperties[0].Value); Assert.Equal("Hello {Planet}", ilogger.LastLogProperties[1].Value); }
public GMLogger() { var config = new NLog.Config.LoggingConfiguration(); var layout = "${time} [${level:}] - ${ndc}${message}"; memoryTarget = new NLog.Targets.MemoryTarget(); memoryTarget.Layout = layout; var fileTarget = new NLog.Targets.FileTarget(); fileTarget.FileName = "gm-log.txt"; fileTarget.Layout = layout; config.AddRuleForOneLevel(LogLevel.Error, memoryTarget); config.AddRuleForOneLevel(LogLevel.Warn, memoryTarget); config.AddRuleForOneLevel(LogLevel.Info, memoryTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; }
static void Main(string[] args) { Config config = new Config(); //Load config file try { string jsonConfig = File.ReadAllText("config.json"); config = JsonSerializer.Deserialize<Config>(jsonConfig); } catch (Exception ex) { Console.Error.WriteLine("Error while reading config file {0}", ex.Message); System.Environment.Exit(-1); } //Initialize logger var nlogConfig = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = config.LogFileName, DeleteOldFileOnStartup = true, Layout = "${longdate} : ${callsite} : ${message}" }; // set logging rules nlogConfig.AddRuleForAllLevels(logfile); // Apply config NLog.LogManager.Configuration = nlogConfig; Worker worker = new Worker(LogManager.GetCurrentClassLogger(), config); worker.Initialize(); worker.Start(); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); worker.Stop(); } // Main
static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Config config = new Config(); //Load config file try { string jsonConfig = File.ReadAllText("config.json"); config = JsonSerializer.Deserialize <Config>(jsonConfig); } catch (Exception ex) { Console.Error.WriteLine("Error while reading config file {0}", ex.Message); System.Environment.Exit(-1); } //Initialize logger var nlogConfig = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = config.LogFileName, DeleteOldFileOnStartup = true, Layout = "${longdate} : ${callsite} : ${message}" }; // set logging rules nlogConfig.AddRuleForAllLevels(logfile); // Apply config NLog.LogManager.Configuration = nlogConfig; Application.Run(new frmMain(LogManager.GetCurrentClassLogger(), config)); }
public void LogEventDropped_OnRequestqueueOverflow() { int queueLimit = 2; int loggedEventCount = 5; int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, QueueLimit = queueLimit, TimeToSleepBetweenBatches = 500, // Make it slow OverflowAction = AsyncTargetWrapperOverflowAction.Discard, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.LogEventDropped += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(loggedEventCount - queueLimit, eventsCounter); } finally { logFactory.Configuration = null; } }
public static void Main(string[] args) { var pathToExe = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); var pathToContentRoot = AppDomain.CurrentDomain.BaseDirectory; NLog.LayoutRenderers.LayoutRenderer.Register("startupdir", (logEvent) => pathToContentRoot); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("allfile") { FileName = @"${startupdir}\logs\nlog-all-${shortdate}.log" }; config.AddRuleForAllLevels(logfile); NLog.LogManager.Configuration = config; var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Trace($"Executable path: {pathToExe}"); logger.Trace($"AppContext.BaseDirectory: {AppContext.BaseDirectory}"); CreateHostBuilder(args).Build().Run(); }