Esempio n. 1
2
        void RunNLog(long iterations)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("Testing NLog messages...");

            var config = new NLog.Config.LoggingConfiguration();
            var fileTarget = new NLog.Targets.FileTarget();
            fileTarget.FileName = @"log\nlog.txt";
            fileTarget.Layout = "${date:format=yyyy-MM-dd.HH.mm.ss.ffffff} ${processid}/${threadid} ${level}: ${message}";
            var asyncWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget, 1000, NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Grow);
            //config.AddTarget("file", asyncWrapper);
            var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, asyncWrapper);
            config.LoggingRules.Add(rule);
            NLog.LogManager.Configuration = config;
            var logger = NLog.LogManager.GetLogger("Benchmark");

            // Prepare strings to write because string concatenation also takes some time
            string[] strings = new string[iterations];
            for (long i = 1; i <= iterations; i++)
            {
                strings[i - 1] = "Benchmark message - " + i;
            }

            stopwatch.Start();

            long percent = 0;
            for (long i = 1; i <= iterations; i++)
            {
                if (showProgress)
                {
                    long newPercent = i * 100 / iterations;
                    if (newPercent > percent)
                    {
                        percent = newPercent;
                        Console.CursorLeft = 0;
                        Console.Write("  " + percent.ToString("##0") + " %");
                    }
                }

                switch (messageType)
                {
                    case 0:
                        logger.Trace("Benchmark message - " + i);
                        break;
                    case 1:
                        logger.Trace(strings[i - 1]);
                        break;
                    case 2:
                        logger.Trace("Benchmark message");
                        break;
                }
            }
            Console.CursorLeft = 0;
            Console.Write("          ");
            Console.CursorLeft = 0;

            stopwatch.Stop();

            long nanoseconds = (long) Math.Round((decimal) stopwatch.ElapsedTicks / Stopwatch.Frequency * 1000000000 / iterations);
            nanoseconds -= emptyLoopTime;
            Console.WriteLine("  " + nanoseconds.ToString().PadLeft(8) + " ns/call");

            // Make sure all log items are written, as long as we have the time to wait for it
            Stopwatch flFlushStopwatch = new Stopwatch();
            flFlushStopwatch.Start();
            NLog.LogManager.Flush();
            flFlushStopwatch.Stop();
            Console.WriteLine("Flushing NLog to files took " + flFlushStopwatch.ElapsedMilliseconds + " ms");
            Console.WriteLine();

            GC.Collect();
        }
Esempio n. 2
0
        static Logger()
        {
            var config     = new NLog.Config.LoggingConfiguration();
            var fileTarget =
                new NLog.Targets.Wrappers.AsyncTargetWrapper(
                    new NLog.Targets.FileTarget()
            {
                FileName = (string)ClientSettings.Instance.ClientLogLocation,
                ArchiveOldFileOnStartup = true,
                KeepFileOpen            = true,
                MaxArchiveFiles         = 10,
                EnableFileDelete        = true,
                CreateDirs = true,
                Layout     = "${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:innerFormat=ToString:maxInnerExceptionLevel=128:innerExceptionSeparator=String:separator = String:format = ToString}"
            },
                    10000, NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Grow);

            config.AddTarget("logfile", fileTarget);

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*",
                                                                LogLevel.FromString(GlobalSettings.Instance.LogLevel), fileTarget));

            LogManager.Configuration = config;

            logger = LogManager.GetLogger("Client");
        }
Esempio n. 3
0
        public void Should_preserve_correct_callsite_information()
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var target  = new MemoryTarget();
            var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(target)
            {
                TimeToSleepBetweenBatches = 0
            };

            config.AddTarget("target", wrapper);

            // Step 3. Set target properties
            target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";

            // Step 4. Define rules
            var rule = new LoggingRule("*", LogLevel.Debug, wrapper);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;
            var factory = new NLogFactory(config);
            var logger  = factory.Create("MyLoggerName");

            WriteLogMessage(logger);
            LogManager.Flush();
            var logMessage = target.Logs[0];

            Assert.Contains("MyLoggerName", logMessage);

            // See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger
            target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}";
            LogManager.ReconfigExistingLoggers();
            WriteLogMessage(logger);
            LogManager.Flush();
            logMessage = target.Logs[1];
            Assert.Contains("CallSiteTests.WriteLogMessage", logMessage);

            // See that LogManager.ReconfigExistingLoggers() is able to upgrade the Logger
            target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message} ThreadId=${threadid}";
            LogManager.ReconfigExistingLoggers();
            WriteLogMessage(logger);
            LogManager.Flush();
            logMessage = target.Logs[2];
            Assert.Contains("ThreadId=" + Thread.CurrentThread.ManagedThreadId.ToString(), logMessage);

            // See that interface logging also works (Improve support for Microsoft.Extension.Logging.ILogger replacement)
            INLogLogger ilogger = logger;

            WriteLogMessage(ilogger);
            LogManager.Flush();
            logMessage = target.Logs[3];
            Assert.Contains("CallSiteTests.WriteLogMessage", logMessage);
        }
Esempio n. 4
0
        private static void SetNLogConfig()
        {
            var config       = new NLog.Config.LoggingConfiguration();
            var asyncWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(new NLog.Targets.FileTarget()
            {
                ArchiveAboveSize = 10000000, FileName = "${basedir}/logs/${shortdate}.log", Name = "f", Layout = "${longdate} ${uppercase:${level}} ${message}"
            });

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, asyncWrapper));
            LogManager.Configuration = config;
        }
Esempio n. 5
0
        public static void SetLoggerConfigurationManually()
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Создадим Targets для async обёртки
            var logRequests = new NLog.Targets.FileTarget("logRequests");

            logRequests.FileName         = "${basedir}/logs/httpRequests.txt";
            logRequests.ArchiveFileName  = "${basedir}/logs/archive/httpRequests.{####}.txt";
            logRequests.ArchiveAboveSize = 10000240;

            var logTroubles = new NLog.Targets.FileTarget("logTroubles");

            logTroubles.FileName         = "${basedir}/logs/troubles.txt";
            logTroubles.ArchiveFileName  = "${basedir}/logs/archive/troubles.{####}.txt";
            logTroubles.ArchiveAboveSize = 10240;

            var logConsole = new NLog.Targets.ColoredConsoleTarget("logconsole");

            logConsole.UseDefaultRowHighlightingRules = true;

            var logDirectoryEvents = new NLog.Targets.FileTarget("logDirectoryEvents");

            logTroubles.FileName         = "${basedir}/logs/directoryEvents.txt";
            logTroubles.ArchiveFileName  = "${basedir}/logs/archive/directoryEvents.{####}.txt";
            logTroubles.ArchiveAboveSize = 10240;

            // Создадим обёртки для асинхронных записей
            var asyncTargetWrapper1 = new NLog.Targets.Wrappers.AsyncTargetWrapper(logRequests);
            var asyncTargetWrapper2 = new NLog.Targets.Wrappers.AsyncTargetWrapper(logTroubles);
            var asyncTargetWrapper3 = new NLog.Targets.Wrappers.AsyncTargetWrapper(logConsole);
            var asyncTargetWrapper4 = new NLog.Targets.Wrappers.AsyncTargetWrapper(logDirectoryEvents);

            // Создадим sync targets
            var logBigTroubles = new NLog.Targets.FileTarget("logBigTroubles");

            logBigTroubles.FileName         = "${basedir}/logs/bigTroubles.txt";
            logBigTroubles.ArchiveFileName  = "${basedir}/logs/archive/bigTroubles.{####}.txt";
            logBigTroubles.ArchiveAboveSize = 10240;

            // Зададим Rules
            config.AddRuleForOneLevel(LogLevel.Error, logBigTroubles);
            config.AddRuleForOneLevel(LogLevel.Warn, logTroubles);
            config.AddRuleForOneLevel(LogLevel.Info, logRequests);
            config.AddRuleForOneLevel(LogLevel.Debug, logConsole);
            config.AddRuleForOneLevel(LogLevel.Trace, logDirectoryEvents);

            // Применим Configuration
            NLog.LogManager.Configuration = config;
        }
Esempio n. 6
0
        private static void InitLog()
        {
            var configuration = new NLog.Config.LoggingConfiguration();
            var layout        = @"${longdate}|${level:uppercase=true}|${logger}|${message}${exception:format=tostring}";
            var logfile       = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "console.log",
                Layout   = layout,
            };
            var asyncLogfile = new NLog.Targets.Wrappers.AsyncTargetWrapper(logfile, 5000, NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Discard);

            configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, asyncLogfile);
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = layout,
            };

            configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
            NLog.LogManager.Configuration = configuration;
        }
Esempio n. 7
0
        private static LoggingConfiguration CreateLogConfig(string fileName)
        {
            var fileTarget = new FileTarget()
            {
                FileName = fileName,
                //   Layout = <string layout>,
                KeepFileOpen     = true,
                ArchiveAboveSize = 50000000,
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                //   ArchiveDateFormat = DatePattern
            };

            var asyncFileTarget =
                new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget, 10000, NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block);

            asyncFileTarget.Name = "async_target";

            var config = new LoggingConfiguration();

            config.AddTarget(asyncFileTarget);
            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, asyncFileTarget);
            return(config);
        }
Esempio n. 8
0
        /// <summary>
        /// Sets the config.
        /// </summary>
        /// <param name="connectionstring">The connectionstring.</param>
        /// <param name="console">The console.</param>
        /// <param name="file">The file.</param>
        /// <param name="database">The database.</param>
        /// <returns></returns>
        public static LoggingConfiguration SetConfig(string connectionstring, bool?console = null, bool?file = null, bool?database = null)
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            #region Console

            if (console.HasValue ? console.Value :  true)
            {
                // Step 2. Create targets and add them to the configuration
                var consoleTarget = new TraceTarget();
                config.AddTarget("console", consoleTarget);

                // Step 3. Set target properties
                consoleTarget.Layout = string.Format("${{date:format=HH\\:mm\\:ss.fff}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{message}} ${{event-context:item={2}}} ${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJSonSession, NLogJsonRequest, NLogCorrId);

                // Step 4. Define rules

                LogLevel level = LogLevel.Trace;

                var rule1 = new LoggingRule("*", level, consoleTarget);
                config.LoggingRules.Add(rule1);
            }

            #endregion

            #region File

            if (file.HasValue ? file.Value :  !console.GetValueOrDefault())
            {
                var fileTarget       = new FileTarget();
                var asyncwrapperFile = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget);
                //            fileTarget.FileName = string.Format("${{basedir}}\\{{$event-context:item={0}}}\\${{shortdate}}_${{level}}.log", NLogApplication);
                fileTarget.FileName = string.Format("{0}/${{shortdate}}_${{level}}.log", "${basedir}/log");
                fileTarget.Layout   = string.Format("\n${{date:format=HH\\:mm\\:ss}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{event-context:item={2}}}\n${{message}}\n${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJsonRequest, NLogJSonSession, NLogCorrId);
                config.AddTarget("file", asyncwrapperFile);

                LogLevel level = LogLevel.Error;
                var      rule2 = new LoggingRule("*", level, asyncwrapperFile);
                // filter na vstupne parametre
                rule2.Filters.Add(new ConditionBasedFilter {
                    Condition = "equals('${logger}','StringMapTypeDeserializer')", Action = FilterResult.Ignore
                });
                config.LoggingRules.Add(rule2);
            }

            #endregion

            #region Database

            if (database.HasValue ? database.Value : true)
            {
                var databaseTarget = new DatabaseTarget();
                //  NLog.Targets.Wrappers.AsyncTargetWrapper asyncwrapperDb = new NLog.Targets.Wrappers.AsyncTargetWrapper(databaseTarget);
                databaseTarget.ConnectionString = connectionstring;
                databaseTarget.CommandText      = "set context_info 0x50006F00730074004400650070006C006F007900;INSERT INTO [reg].[D_Log]([Application],[Version],[machine],[Log_Level],[Logger],[Verb],[RequestUrl],[JsonSession],[JsonRequest],[Message],[LastSoapRequestMessage],[LastSoapResponseMessage],[ErrorType],[ErrorIdentifier],[CorrId]) VALUES (@Application,@Version,@machine,@Log_Level,@Logger,@Verb,@RequestUrl,@JsonSession,@JsonRequest,@Message,@LastSoapRequestMessage,@LastSoapResponseMessage,@ErrorType,@ErrorIdentifier,@CorrId)";
                databaseTarget.KeepConnection   = false;
                databaseTarget.Name             = "DLog";

                var param = new DatabaseParameterInfo();
                param.Name   = "@Application";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogApplication);
                databaseTarget.Parameters.Add(param);

                /*param = new DatabaseParameterInfo();
                 * param.Name = "@Time_Stamp";
                 * param.Layout = "${date}";
                 * databaseTarget.Parameters.Add(param);
                 */
                param        = new DatabaseParameterInfo();
                param.Name   = "@Log_Level";
                param.Layout = "${level}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Logger";
                param.Layout = "${logger}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Verb";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogVerb);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@RequestUrl";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogRequestUrl);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@JsonSession";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogJSonSession);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@JsonRequest";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogJsonRequest);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Version";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogAppVersion);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@LastSoapRequestMessage";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogLastSoapRequestMessage);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@LastSoapResponseMessage";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogLastSoapResponseMessage);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@CorrId";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogCorrId);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@machine";
                param.Layout = "${machinename}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Message";
                param.Layout = "${message}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@ErrorType";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogExceptionType);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@ErrorIdentifier";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogExceptionId);
                databaseTarget.Parameters.Add(param);

                //config.AddTarget("database", asyncwrapperDb);
                config.AddTarget("database", databaseTarget);

                LogLevel level  = LogLevel.Warn;
                var      ruleDb = new LoggingRule("*", level, databaseTarget);
                // filter na vstupne parametre
                ruleDb.Filters.Add(new ConditionBasedFilter {
                    Condition = "equals('${logger}','StringMapTypeDeserializer')", Action = FilterResult.Ignore
                });

                // ruleDb.Filters.Add(new NLog.Filters.Filter());
                //var ruleDb = new LoggingRule("*", LogLevel.Error, asyncwrapperDb);
                config.LoggingRules.Add(ruleDb);
            }

            #endregion

            #region GrayLog

            /*
             * var greyLogHost = WebConfigurationManager.AppSettings["GreyLogHost"];
             * if (!string.IsNullOrEmpty(greyLogHost))
             * {
             *  var greyLogHostParsed = greyLogHost.Split(':');
             *  if (greyLogHostParsed.Length >= 3 && int.TryParse(greyLogHostParsed[2], out int remotePort))
             *  {
             *      var assembly = System.Reflection.Assembly.Load("EasyGelf.NLog");
             *      ConfigurationItemFactory.Default.RegisterItemsFromAssembly(assembly);
             *
             *      EasyGelf.NLog.GelfTargetBase gelfTarget = null;
             *      var remoteAddress = greyLogHostParsed[0];
             *      var transportType = greyLogHostParsed[1];
             *      LogLevel level = (greyLogHostParsed.Length > 3 ? string.IsNullOrEmpty(greyLogHostParsed[3]) : true) ? LogLevel.Trace : LogLevel.FromString(greyLogHostParsed[3]);
             *
             *      if (transportType == "tcp")
             *      {
             *          gelfTarget = new EasyGelf.NLog.GelfTcpTarget()
             *          {
             *              Facility = WebEasNLogLogger.Application,
             *              RemoteAddress = remoteAddress,
             *              RemotePort = remotePort
             *          };
             *      }
             *
             *      if (transportType == "udp")
             *      {
             *          gelfTarget = new EasyGelf.NLog.GelfUdpTarget()
             *          {
             *              Facility = WebEasNLogLogger.Application,
             *              RemoteAddress = remoteAddress,
             *              RemotePort = remotePort
             *          };
             *      }
             *
             *      if (gelfTarget != null)
             *      {
             *          config.AddTarget("gelfTarget", gelfTarget);
             *          gelfTarget.Layout = string.Format("${{date:format=HH\\:MM\\:ss}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{message}} ${{event-context:item={2}}} ${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJSonSession, NLogJsonRequest, NLogCorrId);
             *          //gelfTarget.Layout = "${message}";
             *          config.LoggingRules.Add(new LoggingRule("*", level, gelfTarget));
             *      }
             *  }
             * }
             */
            #endregion
            // Step 5. Activate the configuration
            LogManager.Configuration   = config;
            LogManager.ThrowExceptions = true;
            LogManager.ReconfigExistingLoggers();

            return(config);
        }
        public static void InitializeLog (string logFileName = null, string logLevel = null)
        {
            // default parameters initialization from config file
            if (String.IsNullOrEmpty (logFileName))
            {
                logFileName = System.Configuration.ConfigurationManager.AppSettings["logFilename"] ?? ("${basedir}/log/default_log_name.log");
            }
            if (String.IsNullOrEmpty (logLevel))
            {
                logLevel = System.Configuration.ConfigurationManager.AppSettings["logLevel"] = "Info";
            }   

            // Trying to Parse log Level
            LogLevel currentLogLevel;
            try 
            { 
                currentLogLevel   = LogLevel.FromString (logLevel); 
            }
            catch 
            { 
                currentLogLevel = LogLevel.Info; 
            }

            // Preparing Log Configuration
            var config = new NLog.Config.LoggingConfiguration ();

            // Console Output Config
            if (!Console.IsOutputRedirected)
            {
                var consoleTarget    = new NLog.Targets.ColoredConsoleTarget ();
                consoleTarget.Layout = "${longdate}\t${callsite}\t${level}\t${message}\t${onexception: \\:[Exception] ${exception:format=tostring}}";

                config.AddTarget ("console", consoleTarget);

                var rule1 = new NLog.Config.LoggingRule ("*", LogLevel.Trace, consoleTarget);
                config.LoggingRules.Add (rule1);
            }

            // File Output
            var fileTarget                    = new NLog.Targets.FileTarget ();
            fileTarget.FileName               = "${basedir}/log/" + logFileName;
            fileTarget.Layout                 = "${longdate}\t${callsite}\t${level}\t\"${message}${onexception: \t [Exception] ${exception:format=tostring}}\"";
            fileTarget.ConcurrentWrites       = true;
            fileTarget.AutoFlush              = true;
            fileTarget.KeepFileOpen           = true;
            fileTarget.DeleteOldFileOnStartup = false;
            fileTarget.ArchiveAboveSize       = 2 * 1024 * 1024;  // 2 Mb
            fileTarget.MaxArchiveFiles        = 10;
            fileTarget.ArchiveNumbering       = NLog.Targets.ArchiveNumberingMode.Date;
            fileTarget.ArchiveDateFormat      = "yyyyMMdd_HHmmss";

            // Setting output file writing to Async Mode
            var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper (fileTarget);

            // Adding "File" as one of the log targets
            config.AddTarget ("file", wrapper);

            // Configuring Log from Config File          
            fileTarget.FileName = logFileName;
            var rule2 = new NLog.Config.LoggingRule ("*", currentLogLevel, fileTarget);
            config.LoggingRules.Add (rule2);

            // Saving Configurations
            LogManager.Configuration = config;
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            bool asyncLogging       = false;
            bool useMessageTemplate = false;
            int  threadCount        = 8;
            int  messageCount       = asyncLogging ? 5000000 : 5000000;
            int  messageSize        = 30;
            int  messageArgCount    = 2;

            var fileTarget = new NLog.Targets.FileTarget
            {
                Name                 = "FileTarget",
                FileName             = @"C:\Temp\LibLogPerformance\NLog.txt",
                KeepFileOpen         = true,
                ConcurrentWrites     = false,
                AutoFlush            = false,
                OpenFileFlushTimeout = 1,
            };

            var asyncFileTarget = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget)
            {
                TimeToSleepBetweenBatches = 0,
                OverflowAction            = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block,
                BatchSize = 500
            };

            var benchmarkTool = new BenchmarkTool.BenchMarkExecutor(messageSize, messageArgCount, useMessageTemplate);

            if (!asyncLogging)
            {
                var nlogConfig = new NLog.Config.LoggingConfiguration();
                nlogConfig.AddRuleForAllLevels(fileTarget);
                NLog.LogManager.Configuration = nlogConfig;
            }
            else
            {
                var nlogConfig = new NLog.Config.LoggingConfiguration();
                nlogConfig.AddRuleForAllLevels(asyncFileTarget);
                NLog.LogManager.Configuration = nlogConfig;
            }

            LogProvider.SetCurrentLogProvider(new Logging.LogProviders.NLogLogProvider());
            var nLogger = LogProvider.GetCurrentClassLogger();
            Action <string, object[]> nlogMethod = (messageFormat, messageArgs) =>
            {
                nLogger.Info(messageFormat, messageArgs);
            };
            Action nlogFlushMethod = () =>
            {
                NLog.LogManager.Shutdown();
            };

            benchmarkTool.ExecuteTest(asyncLogging ? "NLog Async" : "NLog", threadCount, messageCount, nlogMethod, nlogFlushMethod);

            if (!asyncLogging)
            {
                var serilogConfig = new LoggerConfiguration()
                                    .WriteTo.File(@"C:\Temp\LibLogPerformance\Serilog.txt", buffered: true, flushToDiskInterval: TimeSpan.FromMilliseconds(1000));
                Log.Logger = serilogConfig.CreateLogger();
            }
            else
            {
                var serilogConfig = new LoggerConfiguration()
                                    .WriteTo.Async(a => a.File(@"C:\Temp\LibLogPerformance\SerilogAsync.txt", buffered: true, flushToDiskInterval: TimeSpan.FromMilliseconds(1000)), blockWhenFull: true);
                Log.Logger = serilogConfig.CreateLogger();
            }

            LogProvider.SetCurrentLogProvider(new Logging.LogProviders.SerilogLogProvider());
            var seriLogger = LogProvider.GetCurrentClassLogger();
            Action <string, object[]> serilogMethod = (messageFormat, messageArgs) =>
            {
                seriLogger.Info(messageFormat, messageArgs);
            };
            Action serilogFlushMethod = () =>
            {
                Log.CloseAndFlush();
            };

            benchmarkTool.ExecuteTest(asyncLogging ? "Serilog Async" : "Serilog", threadCount, messageCount, serilogMethod, serilogFlushMethod);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Esempio n. 11
0
        void RunNLog(long iterations)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("Testing NLog messages...");

            var config     = new NLog.Config.LoggingConfiguration();
            var fileTarget = new NLog.Targets.FileTarget();

            fileTarget.FileName = @"log\nlog.txt";
            fileTarget.Layout   = "${date:format=yyyy-MM-dd.HH.mm.ss.ffffff} ${processid}/${threadid} ${level}: ${message}";
            var asyncWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget, 1000, NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Grow);
            //config.AddTarget("file", asyncWrapper);
            var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, asyncWrapper);

            config.LoggingRules.Add(rule);
            NLog.LogManager.Configuration = config;
            var logger = NLog.LogManager.GetLogger("Benchmark");

            // Prepare strings to write because string concatenation also takes some time
            string[] strings = new string[iterations];
            for (long i = 1; i <= iterations; i++)
            {
                strings[i - 1] = "Benchmark message - " + i;
            }

            stopwatch.Start();

            long percent = 0;

            for (long i = 1; i <= iterations; i++)
            {
                if (showProgress)
                {
                    long newPercent = i * 100 / iterations;
                    if (newPercent > percent)
                    {
                        percent            = newPercent;
                        Console.CursorLeft = 0;
                        Console.Write("  " + percent.ToString("##0") + " %");
                    }
                }

                switch (messageType)
                {
                case 0:
                    logger.Trace("Benchmark message - " + i);
                    break;

                case 1:
                    logger.Trace(strings[i - 1]);
                    break;

                case 2:
                    logger.Trace("Benchmark message");
                    break;
                }
            }
            Console.CursorLeft = 0;
            Console.Write("          ");
            Console.CursorLeft = 0;

            stopwatch.Stop();

            long nanoseconds = (long)Math.Round((decimal)stopwatch.ElapsedTicks / Stopwatch.Frequency * 1000000000 / iterations);

            nanoseconds -= emptyLoopTime;
            Console.WriteLine("  " + nanoseconds.ToString().PadLeft(8) + " ns/call");

            // Make sure all log items are written, as long as we have the time to wait for it
            Stopwatch flFlushStopwatch = new Stopwatch();

            flFlushStopwatch.Start();
            NLog.LogManager.Flush();
            flFlushStopwatch.Stop();
            Console.WriteLine("Flushing NLog to files took " + flFlushStopwatch.ElapsedMilliseconds + " ms");
            Console.WriteLine();

            GC.Collect();
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            bool asyncLogging       = true;
            bool useMessageTemplate = false;
            int  threadCount        = 4;
            int  messageCount       = asyncLogging ? 5000000 : 2000000;
            int  messageSize        = 128;
            int  messageArgCount    = 3;

            var fileTarget = new NLog.Targets.FileTarget
            {
                Name                 = "FileTarget",
                FileName             = @"C:\Temp\MicrosoftPerformance\NLog.txt",
                KeepFileOpen         = true,
                ConcurrentWrites     = false,
                AutoFlush            = false,
                OpenFileFlushTimeout = 1,
            };

            var asyncFileTarget = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget)
            {
                TimeToSleepBetweenBatches = 0,
                OverflowAction            = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block,
                BatchSize = 500
            };

            var benchmarkTool = new BenchmarkTool.BenchMarkExecutor(messageSize, messageArgCount, useMessageTemplate);

            if (!asyncLogging)
            {
                var nlogConfig = new NLog.Config.LoggingConfiguration();
                nlogConfig.AddRuleForAllLevels(fileTarget);
                NLog.LogManager.Configuration = nlogConfig;
            }
            else
            {
                var nlogConfig = new NLog.Config.LoggingConfiguration();
                nlogConfig.AddRuleForAllLevels(asyncFileTarget);
                NLog.LogManager.Configuration = nlogConfig;
            }

            var nlogProvider    = new ServiceCollection().AddLogging(cfg => cfg.AddNLog()).BuildServiceProvider();
            var nLogger         = nlogProvider.GetService <ILogger <Program> >();
            var messageTemplate = benchmarkTool.MessageTemplates[0];
            Action <string, object[]> nlogMethod = null;

            if (messageArgCount == 0)
            {
                nlogMethod = LoggerMessageDefineEmpty(nLogger, messageTemplate);
            }
            else if (messageArgCount == 1)
            {
                nlogMethod = LoggerMessageDefineOneArg(nLogger, messageTemplate);
            }
            else if (messageArgCount == 2)
            {
                nlogMethod = LoggerMessageDefineTwoArg(nLogger, messageTemplate);
            }
            else if (messageArgCount == 3)
            {
                nlogMethod = LoggerMessageDefineThreeArg(nLogger, messageTemplate);
            }
            else
            {
                nlogMethod = (messageFormat, messageArgs) => { nLogger.LogInformation(messageFormat, messageArgs); };
            }
            Action nlogFlushMethod = () =>
            {
                NLog.LogManager.Shutdown();
                nlogProvider.Dispose();
            };

            benchmarkTool.ExecuteTest(asyncLogging ? "NLog Async" : "NLog", threadCount, messageCount, nlogMethod, nlogFlushMethod);

            if (!asyncLogging)
            {
                var serilogConfig = new LoggerConfiguration()
                                    .WriteTo.File(@"C:\Temp\MicrosoftPerformance\Serilog.txt", buffered: true, flushToDiskInterval: TimeSpan.FromMilliseconds(1000));
                Log.Logger = serilogConfig.CreateLogger();
            }
            else
            {
                var serilogConfig = new LoggerConfiguration()
                                    .WriteTo.Async(a => a.File(@"C:\Temp\MicrosoftPerformance\SerilogAsync.txt", buffered: true, flushToDiskInterval: TimeSpan.FromMilliseconds(1000)), blockWhenFull: true);
                Log.Logger = serilogConfig.CreateLogger();
            }

            var serilogProvider = new ServiceCollection().AddLogging(cfg => cfg.AddSerilog()).BuildServiceProvider();
            var serilogLogger   = serilogProvider.GetService <ILogger <Program> >();
            Action <string, object[]> serilogMethod = null;

            if (messageArgCount == 0)
            {
                serilogMethod = LoggerMessageDefineEmpty(serilogLogger, messageTemplate);
            }
            else if (messageArgCount == 1)
            {
                serilogMethod = LoggerMessageDefineOneArg(serilogLogger, messageTemplate);
            }
            else if (messageArgCount == 2)
            {
                serilogMethod = LoggerMessageDefineTwoArg(serilogLogger, messageTemplate);
            }
            else if (messageArgCount == 3)
            {
                serilogMethod = LoggerMessageDefineThreeArg(serilogLogger, messageTemplate);
            }
            else
            {
                serilogMethod = (messageFormat, messageArgs) => { serilogLogger.LogInformation(messageFormat, messageArgs); };
            }
            Action serilogFlushMethod = () =>
            {
                Log.CloseAndFlush();
                serilogProvider.Dispose();
            };

            benchmarkTool.ExecuteTest(asyncLogging ? "Serilog Async" : "Serilog", threadCount, messageCount, serilogMethod, serilogFlushMethod);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //Configures the richtextbox target for showing log
            Dispatcher.Invoke(() =>
            {
                var target = new Helper.WpfRichTextBoxTarget
                {
                    Name = "RichText",
                    Layout =
                        "[${longdate:useUTC=false}] :: [${level:uppercase=true}] :: ${logger}:${callsite} :: ${message} ${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}",
                    ControlName = LogRichTextBox.Name,
                    FormName = GetType().Name,
                    AutoScroll = true,
                    MaxLines = 100000,
                    UseDefaultRowColoringRules = true,
                };
                var asyncWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper { Name = "RichTextAsync", WrappedTarget = target };

                LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper);
                LogManager.Configuration.LoggingRules.Insert(0, new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, asyncWrapper));
                LogManager.ReconfigExistingLoggers();

            });
        }
Esempio n. 14
0
        public static void InitializeLog(string logFileName = null, string logLevel = null)
        {
            // default parameters initialization from config file
            if (String.IsNullOrEmpty(logFileName))
            {
                logFileName = System.Configuration.ConfigurationManager.AppSettings["logFilename"] ?? ("${basedir}/log/default_log_name.log");
            }
            if (String.IsNullOrEmpty(logLevel))
            {
                logLevel = System.Configuration.ConfigurationManager.AppSettings["logLevel"] = "Info";
            }

            // Trying to Parse log Level
            LogLevel currentLogLevel;

            try
            {
                currentLogLevel = LogLevel.FromString(logLevel);
            }
            catch
            {
                currentLogLevel = LogLevel.Info;
            }

            // Preparing Log Configuration
            var config = new NLog.Config.LoggingConfiguration();

            // Console Output Config
            if (!Console.IsOutputRedirected)
            {
                var consoleTarget = new NLog.Targets.ColoredConsoleTarget();
                consoleTarget.Layout = "${longdate}\t${callsite}\t${level}\t${message}\t${onexception: \\:[Exception] ${exception:format=tostring}}";

                config.AddTarget("console", consoleTarget);

                var rule1 = new NLog.Config.LoggingRule("*", LogLevel.Trace, consoleTarget);
                config.LoggingRules.Add(rule1);
            }

            // File Output
            var fileTarget = new NLog.Targets.FileTarget();

            fileTarget.FileName               = "${basedir}/log/" + logFileName;
            fileTarget.Layout                 = "${longdate}\t${callsite}\t${level}\t\"${message}${onexception: \t [Exception] ${exception:format=tostring}}\"";
            fileTarget.ConcurrentWrites       = true;
            fileTarget.AutoFlush              = true;
            fileTarget.KeepFileOpen           = true;
            fileTarget.DeleteOldFileOnStartup = false;
            fileTarget.ArchiveAboveSize       = 2 * 1024 * 1024;  // 2 Mb
            fileTarget.MaxArchiveFiles        = 10;
            fileTarget.ArchiveNumbering       = NLog.Targets.ArchiveNumberingMode.Date;
            fileTarget.ArchiveDateFormat      = "yyyyMMdd_HHmmss";

            // Setting output file writing to Async Mode
            var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget);

            // Adding "File" as one of the log targets
            config.AddTarget("file", wrapper);

            // Configuring Log from Config File
            fileTarget.FileName = logFileName;
            var rule2 = new NLog.Config.LoggingRule("*", currentLogLevel, fileTarget);

            config.LoggingRules.Add(rule2);

            // Saving Configurations
            LogManager.Configuration = config;
        }