Exemplo 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();
        }
Exemplo n.º 2
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;
        }
        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();

            });
        }