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
1
 static void Main(string[] args)
 {
     var config = new NLog.Config.LoggingConfiguration();
     using (var fluentdTarget = new NLog.Targets.Fluentd())
     {
         fluentdTarget.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${level}|${callsite}|${logger}|${message}");
         config.AddTarget("fluentd", fluentdTarget);
         config.LoggingRules.Add(new NLog.Config.LoggingRule("demo", LogLevel.Debug, fluentdTarget));
         var loggerFactory = new LogFactory(config);
         var logger = loggerFactory.GetLogger("demo");
         logger.Info("Hello World!");
     }
 }
Esempio n. 3
0
        public static IServiceCollection AddCommonLogging(this IServiceCollection services)
        {
            var properties  = new NameValueCollection();
            var nlogAdapter = new NLogLoggerFactoryAdapter(properties);

            LogManager.Adapter = nlogAdapter;

            var config = new NLog.Config.LoggingConfiguration();

            config.AddTarget("console", new ConsoleTarget
            {
                Layout = "${my-layout}"
            });
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, "console");
            NLog.Config.ConfigurationItemFactory.Default.RegisterItemsFromAssembly(Assembly.GetExecutingAssembly());

            NLog.LogManager.Configuration = config;

            return(services.AddScoped <ILog>(sp =>
            {
                var context = sp.GetRequiredService <DefaultServiceContext>();

                // inject context info to Logger
                NLog.MappedDiagnosticsLogicalContext.Set("corp-id", context.CorpId);
                NLog.MappedDiagnosticsLogicalContext.Set("user-id", context.UserId);

                return LogManager.GetLogger("app");
            }));
        }
Esempio n. 4
0
        public void RunBeforeAnyTests()
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "unit-test.log"
            };
            var logconsole  = new NLog.Targets.ConsoleTarget("logconsole");
            var logdebugger = new NLog.Targets.DebuggerTarget("logdebugger");

            // Rules for mapping loggers to targets
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile);
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logdebugger);

            // Apply config
            NLog.LogManager.Configuration = config;

            var serviceProvider = new ServiceCollection()
                                  .AddLogging(logger =>
            {
                logger.SetMinimumLevel(LogLevel.Trace);
            })
                                  .BuildServiceProvider();

            LogFactory = serviceProvider.GetService <ILoggerFactory>();
            LogFactory.AddNLog();
        }
Esempio n. 5
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //Log
            var logConfig = new NLog.Config.LoggingConfiguration();
            var fileTarget = new NLog.Targets.FileTarget();
            fileTarget.FileName = Configuration["Data:Log:logFile"];
            fileTarget.Name = "FileLogger";
            fileTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger}:${message};${exception}";
            logConfig.AddTarget(fileTarget);
            logConfig.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, fileTarget));
            if (env.IsDevelopment())
            {
                var consoleLogger = new NLog.Targets.ColoredConsoleTarget();
                consoleLogger.Name = "ConsoleLogger";
                consoleLogger.Layout = @"${date:format=HH\:mm\:ss} ${logger}:${message};${exception}";
                logConfig.AddTarget(consoleLogger);
                logConfig.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, consoleLogger));
            }
            LogManager.Configuration = logConfig;

            // Add the platform handler to the request pipeline.
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            LogManager.GetLogger("Website").Info("Started!");
        }
Esempio n. 6
0
 /// <summary>
 /// 自定义输出目录,初始化
 /// </summary>
 public void Setting(string path)
 {
     if (_path != path)
     {
         _path = path;
         Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
         var config  = new NLog.Config.LoggingConfiguration();
         var logfile = new NLog.Targets.FileTarget()
         {
             FileName = "logs/${date:format=yyyyMM}/${shortdate}_log.txt", Encoding = Encoding.GetEncoding("GB2312")
         };
         logfile.KeepFileOpen         = true;
         logfile.OpenFileCacheTimeout = 30;
         logfile.ConcurrentWrites     = false;
         if (!string.IsNullOrEmpty(path))
         {
             path   += "/";
             logfile = new NLog.Targets.FileTarget()
             {
                 FileName = "logs/" + path + "${shortdate}_log.txt", Encoding = Encoding.GetEncoding("GB2312")
             };
         }
         config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile));
         LogManager.Configuration = config;
     }
 }
Esempio n. 7
0
        public static void Register(HttpConfiguration config)
        {
            var fileConfig = new AutoConfigField <FileTarget>(
                key: "logging.file.settings",
                description: "Logger settings for logging to a file",
                defaultVal: new FileTarget()
            {
                Name     = "file",
                Layout   = @"${longdate}|${logger:shortName=true}|${level:uppercase=true}|${message}",
                FileName = @"C:\Users\Nolan\Desktop\${shortdate}.txt",
            }
                );
            var fileLevel = new AutoConfigField <string>(
                key: "logging.file.level",
                description: "What level the file logger should log at",
                defaultVal: "Info"
                );

            // Setup logging
            var logConfig = new NLog.Config.LoggingConfiguration();

            // File logging
            if (!string.Equals("off", fileLevel, StringComparison.InvariantCultureIgnoreCase))
            {
                logConfig.AddTarget(fileConfig);
                logConfig.AddRule(LogLevel.FromString(fileLevel), LogLevel.Off, fileConfig.Value.Name);
            }

            LogManager.Configuration = logConfig;
        }
Esempio n. 8
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            #region Log
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "log/file.txt"
            };
            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            var factory = new NLog.Extensions.Logging.NLogLoggerFactory();
            Microsoft.Extensions.Logging.ILogger logger = factory.CreateLogger("");

            containerRegistry.RegisterInstance <Microsoft.Extensions.Logging.ILogger>(logger);

            var log = Container.Resolve <Microsoft.Extensions.Logging.ILogger>();
            log.LogInformation("Test in RegisterTypes");
            #endregion

            //containerRegistry.RegisterInstance(typeof(ILocalizerService),
            //    "LocalizerService",
            //        new LocalizerService("zh-TW"),
            //            new ContainerControlledLifetimeManager());
            //containerRegistry.RegisterInstance<ILocalizerService, LocalizerService("zh-TW")>(new ContainerControlledLifetimeManager());
            containerRegistry.RegisterSingleton <ILocalizerService, LocalizerService>();

            containerRegistry.RegisterSingleton <IMessageService, MessageService>();

            containerRegistry.RegisterSingleton <IApplicationCommands, ApplicationCommandsProxy>();
            containerRegistry.RegisterInstance <IFlyoutService>(Container.Resolve <FlyoutService>());
        }
Esempio n. 9
0
        static void SetupLogging(string path)
        {
            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName         = path,
                FileNameKind     = NLog.Targets.FilePathKind.Absolute,
                Layout           = "${longdate} ${level:uppercase=true} ${logger}: ${message} ${exception:format=tostring}",
                ArchiveAboveSize = 1024 * 1024 * 8,
                MaxArchiveFiles  = 10
            };

            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${level:uppercase=true} ${logger}: ${message} ${exception:format=tostring}"
            };

#if DEBUG
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
#endif
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            NLog.LogManager.Configuration = config;
        }
Esempio n. 10
0
        static void PrepareLoggers()
        {
            // Step 1. Create configuration object
            var config = new NLog.Config.LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var file = new NLog.Targets.FileTarget("FileLogger");

            config.AddTarget(file);

            // Step 3. Set target properties
            file.ArchiveEvery            = NLog.Targets.FileArchivePeriod.Day;
            file.ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.DateAndSequence;
            file.ArchiveOldFileOnStartup = true;
            file.Layout =
                @"${date:universalTime=true:format=yyyy-MM-ddTHH\:mm\:ss.fffZ}|${level:uppercase=true}|${logger} ${event-properties:item=logSource}|${message}";
            file.LineEnding = NLog.Targets.LineEndingMode.LF;
            file.FileName   = "mpm.log";

            var console = new NLog.Targets.ConsoleTarget("console");

            config.AddTarget(console);
            console.Layout =
                @"[${date:universalTime=false:format=yyyy-MM-ddTHH\:mm\:ss.fffzzz}][${level:uppercase=true}][${logger}]: ${message}";

            // Step 4. Define rules
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, file));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, console));

            NLog.LogManager.Configuration = config;
        }
Esempio n. 11
0
        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();
        }
Esempio n. 12
0
        private static Logger InitializeNlog_V3()
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "${basedir}/logs/Nlog.${shortdate}.log", Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}", Encoding = Encoding.UTF8
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}"
            };

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);

            // Apply config
            LogManager.Configuration = config;

            Logger nlogLogger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();

            return(nlogLogger);
        }
Esempio n. 13
0
        public static void Configure()
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget()
            {
                FileName = "file.txt", Name = "logfile"
            };

            logfile.Layout = "Level        : ${level} ${newline}When         : ${longdate} ${newline}Message      : ${message} ${newline}Machine Name : ${machinename} ${newline}Stack Trace  : ${stacktrace} ${newline} ";


            //            layout type = "log4net.Layout.PatternLayout" >
            //< IgnoresException value = "False" />

            // ...


            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Error, logfile));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logfile));

            logfile.ArchiveEvery      = FileArchivePeriod.Day;
            logfile.ArchiveNumbering  = ArchiveNumberingMode.Rolling;
            logfile.ConcurrentWrites  = true;
            logfile.KeepFileOpen      = false;
            logfile.ArchiveDateFormat = "yyyyMMdd";

            LogManager.Configuration = config;
        }
Esempio n. 14
0
 public NLoggerFactory(JimuNLogOptions options = null)
 {
     options = options ?? new JimuNLogOptions {
         EnableConsoleLog = true
     };
     if (!string.IsNullOrEmpty(options.Configuration))
     {
         N.LogManager.Configuration = new N.Config.XmlLoggingConfiguration(options.Configuration);
     }
     else
     {
         var config = new N.Config.LoggingConfiguration();
         //var ip = JimuHelper.GetLocalIPAddress();
         if (options.EnableFileLog)
         {
             var fileConf = new N.Targets.FileTarget("jimuLogFile")
             {
                 ArchiveAboveSize = 10000000,
                 Layout           = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} [${threadid}] ${message}"
             };
             string path = string.IsNullOrEmpty(options.FileLogPath) ? "./log" : options.FileLogPath;
             fileConf.FileName = path + "/${shortdate}.log";
             config.AddRule(ConvertToLevel(options.FileLogLevelMin), ConvertToLevel(options.FileLogLevelMax), fileConf);
         }
         if (options.EnableConsoleLog)
         {
             var consoleLog = new N.Targets.ConsoleTarget("jimuLogconsole")
             {
                 Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} [${threadid}] ${message}"
             };
             config.AddRule(ConvertToLevel(options.ConsoleLogLevelMin), ConvertToLevel(options.ConsoleLogLevelMax), consoleLog);
         }
         N.LogManager.Configuration = config;
     }
 }
Esempio n. 15
0
        public void RenderShouldHandleInvalidConversionAndLogFactoryAndDefault()
        {
            // Arrange
            var factory = new LogFactory
            {
                ThrowExceptions = false,
            };
            var configuration = new NLog.Config.LoggingConfiguration(factory);

            var layout = new Layout <int>("${event-properties:prop1}");

            layout.Initialize(configuration);
            var logEventInfo = LogEventInfo.CreateNullEvent();

            logEventInfo.Properties["prop1"] = "Not a int";

            // Act
            int result;

            using (new NoThrowNLogExceptions())
            {
                result = layout.RenderValue(logEventInfo, 200);
            }

            // Assert
            Assert.Equal(200, result);
        }
Esempio n. 16
0
        public static void ConfigureNLog()
        {
            var config = new NLog.Config.LoggingConfiguration();

            var profilerFile = new FileTarget("profilerFile")
            {
                FileName                = $"{AssemblyLocation}/logs/profiler.json",
                ArchiveFileName         = $"{AssemblyLocation}/logs/profiler.{"{####}"}.json",
                Layout                  = "${message}",
                ArchiveNumbering        = ArchiveNumberingMode.Rolling,
                ArchiveOldFileOnStartup = true,
            };

            var errorFile = new FileTarget("errorLogFile")
            {
                FileName = $"{AssemblyLocation}/logs/log.txt",
                Layout   = $"{"${longdate} ${message} ${exception:format=StackTrace:maxInnerExceptionLevel=5}"}",
            };

            Debug.WriteLine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            config.AddTarget("profiler", profilerFile);
            config.AddTarget("error", errorFile);

            config.AddRule(LogLevel.Trace, LogLevel.Trace, profilerFile);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, errorFile);
            LogManager.Configuration = config;
        }
Esempio n. 17
0
        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);
        }
Esempio n. 18
0
        private void SetLoggingPreferences()
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var console = new NLog.Targets.ConsoleTarget("logconsole");

            // Keep loglevel off by default.
            NLog.LogLevel minLogLevel;

            // If both Debug and Verbose are passed, Debug takes priority as NLog.Debug loglevel ranks lower than NLog.Info.
            // We will display all the log levels in between NLOG.Debug to NLog.Fatal(includes NLog.Info).
            if (MyInvocation.BoundParameters.ContainsKey("Debug"))
            {
                minLogLevel = NLog.LogLevel.Debug;
            }
            else if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
            {
                minLogLevel = NLog.LogLevel.Info;
            }
            else
            {
                minLogLevel = NLog.LogLevel.Off;
            }

            config.AddRule(minLogLevel, NLog.LogLevel.Fatal, console);
            NLog.LogManager.Configuration = config;
        }
Esempio n. 19
0
        private static void SetupLogger()
        {
            var config = new NLog.Config.LoggingConfiguration();

            var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole");
            var layout     = new NLog.Layouts.SimpleLayout(
                "[${date:format=HH\\:mm\\:ss}][${level}]${logger:shortName=true}: ${message}"
                );

            logconsole.Layout   = layout;
            logconsole.Encoding = System.Text.Encoding.UTF8;
            var logfile = new NLog.Targets.FileTarget("logfile");

            logfile.FileName          = "./logs/log.txt";
            logfile.ArchiveFileName   = "log.{#}.txt";
            logfile.ArchiveNumbering  = NLog.Targets.ArchiveNumberingMode.Date;
            logfile.ArchiveDateFormat = "dd-MM-yyyy";
            logfile.ArchiveEvery      = NLog.Targets.FileArchivePeriod.Day;
            logfile.CreateDirs        = true;
            logfile.Layout            = layout;
            logfile.Encoding          = System.Text.Encoding.UTF8;

            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logconsole, "*");
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile, "*");

            NLog.LogManager.Configuration = config;
            logger = NLog.LogManager.GetCurrentClassLogger();
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "file.txt"
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            // Apply config
            LogManager.Configuration = config;

            int i = 0;

            while (true)
            {
                try
                {
                    Logger.Info(i++);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Goodbye cruel world");
                    break;
                }
            }

            NLog.LogManager.Shutdown();
        }
Esempio n. 21
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //NLog configuration alternative to NLog.config >>>>
            var config = new NLog.Config.LoggingConfiguration();

            FileTarget logfileTarget1 = new NLog.Targets.FileTarget("NLogExample.Model.ClassSon")
            {
                FileName = "NLogExample.Model.ClassSon.log"
            };
            FileTarget logfileTarget2 = new NLog.Targets.FileTarget("NLogExample.Model.ClassDaughter")
            {
                FileName = "NLogExample.Model.ClassDaughter.log"
            };

            //Format the output lines
            logfileTarget1.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" +
                                                                  "${ callsite:className=true:methodName=true} | ${message} ");
            logfileTarget2.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" +
                                                                  "${ callsite:className=true:methodName=true} | ${message} ");

            //!!LoggerNamePattern parameter is important to split the log strema into the files depending on the class instance!!
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget1, "NLogExample.Model.ClassSon");
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget2, "NLogExample.Model.ClassDaughter");

            NLog.LogManager.Configuration = config;
            //<<<< NLog configuration
        }
Esempio n. 22
0
        public MainWindow()
        {
            InitializeComponent();

            Title = $"报告自动校核 v{Application.ResourceAssembly.GetName().Version.ToString()}";

            //TODO:movetofunction
            Top  = 0.3 * (App.ScreenHeight - Height);
            Left = 0.4 * (App.ScreenWidth - Width);
            //this.Left = ScreenWidth - this.ActualWidth * 1.3;

            //Nlog
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = @"Log\LogFile.txt"
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            // Apply config
            LogManager.Configuration = config;

            log = LogManager.GetCurrentClassLogger();
            CheckForUpdateInStarup();    //启动时检查更新
        }
Esempio n. 23
0
        private static (ILogger, IDisposable) InitializeLogger()
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "log.txt"
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            var dispose = new AnonymousDisposable(() =>
            {
                logfile.Dispose();
                logconsole.Dispose();
            });

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Error, LogLevel.Fatal, logfile);

            // Apply config
            NLog.LogManager.Configuration = config;

            return(NLog.LogManager.GetCurrentClassLogger(), dispose);
        }
Esempio n. 24
0
        public static void Main(string[] args)
        {
            string logFileLocation = PathProvider.GetApplicationDataFolder() + "/gatekeeper-logs.txt";

            NLog.Config.LoggingConfiguration config        = new NLog.Config.LoggingConfiguration();
            NLog.Targets.FileTarget          logFileTarget = new NLog.Targets.FileTarget("logfile")
            {
                FileName = logFileLocation
            };
            NLog.Targets.ConsoleTarget logConsoleTarget = new NLog.Targets.ConsoleTarget("logconsole");
            logFileTarget.Layout    = "${longdate} ${message} ${exception:format=tostring}";
            logConsoleTarget.Layout = "${longdate} ${message} ${exception:format=tostring}";
            config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logConsoleTarget);
            config.AddRule(NLog.LogLevel.Error, NLog.LogLevel.Fatal, logFileTarget);

            NLog.Logger logger = NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger();

            try
            {
                logger.Debug("init main");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }
Esempio n. 25
0
        private void SetupLogger()
        {
            const string format = "${longdate} ${message} ${exception:format=tostring}";
            var          config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget()
            {
                FileName = "SpotifyLyrics.log",
                Name     = "logfile",
                Layout   = new SimpleLayout(format),
                Encoding = Encoding.UTF8,
            };

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile));

#if DEBUG
            var logconsole = new NLog.Targets.ConsoleTarget()
            {
                Name     = "logconsole",
                Layout   = new SimpleLayout(format),
                Encoding = Encoding.UTF8,
            };
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole));
#endif

            NLog.LogManager.Configuration = config;
        }
Esempio n. 26
0
        public static void Initialize(ScriptContext context)
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = GetDefaultLogPath(),
                Layout   = "${date:format=HH\\:mm\\:ss:padding=-10:fixedlength=true} ${gdc:item=Script:padding=-20:fixedlength=true} ${level:uppercase=true:padding=-10:fixedlength=true} ${gdc:item=User:padding=-35:fixedlength=true} ${gdc:item=Patient:padding=-35:fixedlength=true} ${message}${onexception:${newline}  ${exception:format=Message,StackTrace:separator=\r\n}}"
            };

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);

            // Apply config
            LogManager.Configuration = config;

            GlobalDiagnosticsContext.Set("Script", "Dosimetry Helper");
            GlobalDiagnosticsContext.Set("User", $"{context.CurrentUser.Name} ({context.CurrentUser.Id})");
            GlobalDiagnosticsContext.Set("Patient", $"{context.Patient.LastName}, {context.Patient.FirstName} ({context.Patient.Id})");

            // Clear the log every day and save yesterday's log in case there were errors that need to be looked into
            if (File.Exists(GetDefaultLogPath()) && DateTime.Now.Day != File.GetLastWriteTime(GetDefaultLogPath()).Day)
            {
                File.Delete(GetOldLogPath());
                File.Copy(GetDefaultLogPath(), GetOldLogPath());
                File.Delete(GetDefaultLogPath());
            }
        }
Esempio n. 27
0
        public WPFLogger(MainWindow userForm)
        {
            form = userForm;
            //Cleanup old log
            if (File.Exists(Path.Combine(Directory.GetParent(App.GetExecutablePath()).FullName, "CaptureLog.txt")))
            {
                File.Delete(Path.Combine(Directory.GetParent(App.GetExecutablePath()).FullName, "CaptureLog.txt"));
            }

            var             LoggingConfig = new NLog.Config.LoggingConfiguration();
            FileVersionInfo v             = FileVersionInfo.GetVersionInfo(App.GetExecutablePath());
            var             logfile       = new NLog.Targets.FileTarget("logfile")
            {
                FileName                = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/latest.log",
                ArchiveFileName         = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/{#}.log",
                ArchiveNumbering        = ArchiveNumberingMode.Date,
                Layout                  = "${time:universalTime=True} | ${message}",
                MaxArchiveFiles         = 5,
                ArchiveOldFileOnStartup = true,
                ArchiveDateFormat       = "yyyy-MM-dd HH_mm_ss",
                Header                  = $"Capture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}\n",
                Footer                  = $"\nCapture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}"
            };

            LoggingConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = LoggingConfig;
            logger = LogManager.GetLogger("WPFLogger");
        }
Esempio n. 28
0
        public Log()
        {
            var config = new NLog.Config.LoggingConfiguration();

            var assembly = System.Reflection.Assembly.GetEntryAssembly();
            var name     = assembly.GetName().Name;

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget(name)
            {
                FileName = "${basedir}/logs/${logger}/${shortdate}.log",
                Layout   = "${longdate} ${aspnet-request:servervariable=URL}[${uppercase:${level}}] ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=10}"
            };

            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${aspnet-request:servervariable=URL}[${uppercase:${level}}] ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=10}"
            };

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            // Apply config
            NLog.LogManager.Configuration = config;
        }
Esempio n. 29
0
        private static void ConfigureLogging()
        {
            var config = new NLog.Config.LoggingConfiguration();

            var logFile = new NLog.Targets.FileTarget("logfile")
            {
                Layout                  = "${date:format=yyyy-MM-dd HH\\:mm\\:ss.fff}|${level:uppercase=true}|${logger:shortName=True}|${message:withexception=true}",
                FileName                = "./logging/InventoryKamera.log",
                ArchiveFileName         = "logging/archives/InventoryKamera.{####}.log",
                ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.Date,
                ArchiveDateFormat       = "yyyyMMddHHmmss",
                MaxArchiveFiles         = 4,
                ConcurrentWrites        = true,
                KeepFileOpen            = true,
                ArchiveOldFileOnStartup = true,
                ArchiveFileKind         = NLog.Targets.FilePathKind.Relative
            };

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

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logConsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFile);

            LogManager.Configuration = config;
        }
Esempio n. 30
0
        static void Main()
        {
            var config = new NLog.Config.LoggingConfiguration();

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, new ColoredConsoleTarget {
                Layout = new SimpleLayout("${message}")
            });
            LogManager.Configuration = config;

            Console.WriteLine("Welcome to the aoe2ai snippeter!");
            Console.WriteLine("Results will be automatically copied to the clipboard.\n");

            var clipboard  = new Clipboard();
            var transpiler = new Transpiler();

            while (true)
            {
                Console.Write(">");
                var content = Console.ReadLine();

                var result = transpiler.Transpile(content).Render(new IFormatter[] { new IndentedDefrule(), new IndentedCondition() });
                if (!string.IsNullOrWhiteSpace(result))
                {
                    clipboard.SetText(result);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"\n{result}\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
        }
        public void RegisterLogger(string logFilename)
        {
            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget
            {
                FileName = logFilename,
                Name     = "logfile",
                Layout   = "${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString,StackTrace}${newline}"
            };

            var logconsole = new NLog.Targets.ConsoleTarget
            {
                Name   = "logconsole",
                Layout = "${longdate}|${level:uppercase=true}|${logger:shortName=true}|${message}"
            };

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Warn, logfile));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Error, logfile));

            LogManager.Configuration = config;

            _container.RegisterConditional(typeof(ILogger),
                                           context => typeof(NLogProxy <>).MakeGenericType(context.Consumer.ImplementationType),
                                           Lifestyle.Singleton, context => true);
        }
Esempio n. 32
0
        public static void init_logging(logConfig userConfig)
        {
            // Logging
            var config = new NLog.Config.LoggingConfiguration();
            // Targets where to log to: File and Console
            //var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
            var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole");

            LogLevel userLogLevel = LogLevel.Info;

            if (userConfig.logLevel.ToLower() == "debug")
            {
                userLogLevel = LogLevel.Debug;
            }
            if (userConfig.logLevel.ToLower() == "warning")
            {
                userLogLevel = LogLevel.Warn;
            }
            if (userConfig.logLevel.ToLower() == "error")
            {
                userLogLevel = LogLevel.Error;
            }
            if (userConfig.logLevel.ToLower() == "fatal")
            {
                userLogLevel = LogLevel.Fatal;
            }

            // Rules for mapping loggers to targets
            config.AddRule(userLogLevel, LogLevel.Fatal, logconsole);

            // Apply config
            NLog.LogManager.Configuration = config;
        }
Esempio n. 33
0
        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);
        }
        /// <summary>
        /// Setup custom targets and rules
        /// </summary>
        public static void SetupConfig()
        {
            //get current config
            config = NLog.LogManager.Configuration;
            NLog.LogManager.ThrowExceptions = true;
            SetupTargets();

            SetupRules();

            //save config
            NLog.LogManager.Configuration = config;
        }
Esempio n. 35
0
 public Logger(string dir)
 {
     NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
     NLog.Targets.FileTarget fileTarget = new NLog.Targets.FileTarget();
     config.AddTarget("file", fileTarget);
     fileTarget.FileName = System.IO.Path.Combine(dir, "log.txt");
     fileTarget.Layout = "${date:format=MM/dd HH\\:mm\\:ss.ffff}|${level:uppercase=true:padding=6}| ${message}";
     fileTarget.DeleteOldFileOnStartup = true;
     NLog.Config.LoggingRule rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, fileTarget);
     config.LoggingRules.Add(rule);
     NLog.LogManager.Configuration = config;
     logger = NLog.LogManager.GetLogger("OnlineVideos");
 }
Esempio n. 36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudWatchService"/> class.
        /// </summary>
        public CloudWatchService()
        {
            PerformanceCounters = new ConcurrentDictionary<PerformanceCounterDescription, PerformanceCounter>();
            ManagementServiceHost = new WebServiceHost(new ManagementService(this), new Uri(ManagementService.LocalEndpointUrl));
            ManagementServiceHost.AddServiceEndpoint(typeof(IManagementService), new WebHttpBinding(), string.Empty);

            var config = new NLog.Config.LoggingConfiguration();
            config.AddTarget("File", new NLog.Targets.FileTarget()
            {
                FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NCloudWatch", "log.txt")
            });
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, config.FindTargetByName("File")));

            LogManager.Configuration = config;
            logger = LogManager.GetLogger("NCloudWatch");
        }
        public static void MyClassInitialize(TestContext testContext)
        {
            var config = new NLog.Config.LoggingConfiguration();

            var target = new NLog.Targets.DebuggerTarget();

            config.AddTarget("debugger", target);

            var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, target);

            config.LoggingRules.Add(rule);

            NLog.LogManager.Configuration = config;

            var _logger = NLog.LogManager.GetCurrentClassLogger();

            _logger.Debug("Using programmatic config");
        }
Esempio n. 38
0
        internal static void Configurelogging()
        {
            //Assigning an adapter to the loggingfacade, this happens to be NLog, we also need to configure the way NLog gets configured, via FILE or code (INLINE).
            LogManager.Adapter = new NLogLoggerFactoryAdapter(new System.Collections.Specialized.NameValueCollection() { { "configType", "INLINE" } });

            var config = new NLog.Config.LoggingConfiguration();

            var dayTarget = new NLog.Targets.FileTarget() { FileName = "logs\\McManage ${shortdate}.log", Encoding = System.Text.Encoding.UTF8, ConcurrentWrites = false };
            var tailTarget = new NLog.Targets.FileTarget() { FileName = "McManage.log", Encoding = System.Text.Encoding.UTF8, ConcurrentWrites = false, DeleteOldFileOnStartup = true};

            config.AddTarget("dayfile", dayTarget);
            config.AddTarget("tailfile", tailTarget);

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, dayTarget));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, tailTarget));

            NLog.LogManager.Configuration = config;
        }
        public override void Load()
        {
            //Create bindings
            Rebind<IStartupService>().To<StartupService>().InSingletonScope();
            Rebind<IChunk>().To<Chunk>();
            Rebind<INetworkPeer>().To<NetworkPeer>().InSingletonScope();
            string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.Length - Path.GetFileName(Application.ExecutablePath).Length);
            Rebind<IFileSystem>().To<StandardFileSystem>().InSingletonScope().WithConstructorArgument("workingDirectory", new FileReference(path + "assets/"));
            Rebind<NetPeerConfiguration>().ToMethod(context => Kernel.Get<NetworkConfig>().CreateNetPeerConfig()).InSingletonScope();
            Rebind<IConfigManager>().To<ConfigManager>().InSingletonScope().WithConstructorArgument("fileReference", new FileReference(Application.ExecutablePath).GetFileName() + "_config.json");
            Rebind<ActorProvider>().To<ActorProvider>().InSingletonScope();   
            Rebind<IActor>().ToProvider<ActorProvider>();
            
            //Logging config stuff
            {
                NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
                //targets
                NLog.Targets.FileTarget fileTarget = new NLog.Targets.FileTarget();
                config.AddTarget("file", fileTarget);
                NLog.Targets.ConsoleTarget consoleTarget = new NLog.Targets.ConsoleTarget();
                config.AddTarget("console", fileTarget);

                fileTarget.FileName = "${basedir}/${processname}_Log.txt";
                fileTarget.Layout = "[${longdate}] [${level}] [${message}]";
                consoleTarget.Layout = ">> [${date:format=HH\\:MM\\:ss}] [${level}] [${message}]";
                //rules
                NLog.Config.LoggingRule loggingRule;
                loggingRule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(loggingRule);
                loggingRule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, consoleTarget);
                config.LoggingRules.Add(loggingRule);
                //activate
                NLog.LogManager.Configuration = config;
            }

            //Register services - Order is important services bound first get to register for events first and consequently receive events first.
            IStartupService startup = Kernel.Get<IStartupService>();
            startup.RegisterStartupType<IConfigManager>();
            startup.RegisterStartupType<IMessageTypeManager>();
            startup.RegisterStartupType<IBlockManager>();
            startup.RegisterStartupType<IMap>();
        }
Esempio n. 40
0
        public void Aggregate_And_AppendProvider() {

            //def console
            LoggerManager.Factory.AddConsole(LogLevel.Trace);

            _logger.Info("------- console -------");

            var config = new NLog.Config.LoggingConfiguration();

            var consoleTarget = new NLog.Targets.ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);

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

            var factory = new NLog.LogFactory(config);

            //append NLog
            LoggerManager.Factory.AddNLog(factory);

            _logger.Info("------- console & nlog -------");
        }
        public static void MyClassInitialize(TestContext testContext)
        {
            // set up NLog
            var config = new NLog.Config.LoggingConfiguration();
            var dt = new NLog.Targets.DebuggerTarget()
            {
                Layout = "${longdate} ${uppercase:${level}} ${message}",
                Name = "t"
            };
            config.AddTarget("t", dt);
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, dt));
            NLog.LogManager.Configuration = config;
            var logger = NLog.LogManager.GetCurrentClassLogger();
            logger.Info("Test starting");

            // clear existing test objects,
            // create new test objects,
            // get IDs of test objects
            using (var db = new OmbudsmanEntities())
            {
                TestData = db.TestInitialize().Single();
            }
            logger.Info("Facility ID {0}, Ombudsman ID {1}", TestData.Facility1, TestData.Ombudsman1);
        }
		private void SetupLogging(ContainerBuilder builder)
		{
			builder.Register(context =>
					{
						if(_diMode != EnumDIMode.CommandLine)
						{
							//This resolve operation has already ended.  
							//	When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. 
							//	Instead, either resolve IComponentContext again from 'c', or resolve a Func<> based factory to create subsequent components from.
							var c = context.Resolve<IComponentContext>();
							var identity = context.Resolve<IUserIdentity>();
							var dbTarget = new NLogDBLogTarget(new AutofacDIFactory(c), identity);
							dbTarget.Layout = "${message} ${exception:format=message,stacktrace:separator=\r\n}";
							var loggingConfig = NLog.LogManager.Configuration;
							if (loggingConfig == null)
							{
								loggingConfig = new NLog.Config.LoggingConfiguration();
							}
							loggingConfig.AddTarget("dbTarget", dbTarget);
							var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Warn, dbTarget);
							loggingConfig.LoggingRules.Add(rule);
							NLog.LogManager.Configuration = loggingConfig;
						}
						var logger = NLog.LogManager.GetCurrentClassLogger();

						return logger;
					})
					.As<NLog.Logger>()
					.SingleInstance();
            Common.Logging.LogManager.Adapter = new Common.Logging.NLog.NLogLoggerFactoryAdapter((Common.Logging.Configuration.NameValueCollection)null);
            builder.Register(ctx=> 
                    { return Common.Logging.LogManager.GetCurrentClassLogger(); })
                    .As<Common.Logging.ILog>()
                    .SingleInstance();
		}
Esempio n. 43
0
		private static void SetupColorConsoleLogging()
		{
			var loggingConfig = NLog.LogManager.Configuration;
			if (loggingConfig == null)
			{
				loggingConfig = new NLog.Config.LoggingConfiguration();
			}
			var consoleTarget = new NLog.Targets.ColoredConsoleTarget();
			consoleTarget.Layout = "${longdate}:${message} ${exception:format=message,stacktrace=\r\n}";
			loggingConfig.AddTarget("consoleTarget", consoleTarget);
			var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
			loggingConfig.LoggingRules.Add(rule);
			NLog.LogManager.Configuration = loggingConfig;
		}
        /// <summary>
        /// Log initialization.
        /// </summary>
        internal static void InitializeLog (string logFileName = null, string logLevel = null, InitializationOptions options = null)
        {
            if (options != null && !options.overrideNLogFileConfiguration && LogManager.Configuration == null)
                return;

            // default parameters initialization from config file
            if (String.IsNullOrEmpty (logFileName))
                logFileName = _logFileName ?? System.Configuration.ConfigurationManager.AppSettings["logFilename"];
			if (String.IsNullOrEmpty (logFileName))
                logFileName = ("${basedir}/log/" + typeof (ConsoleUtils).Namespace.Replace (".SimpleHelpers", "") + ".log");
            if (String.IsNullOrEmpty (logLevel))
                logLevel = _logLevel ?? (System.Configuration.ConfigurationManager.AppSettings["logLevel"] ?? "Info");

            // check if log was initialized with same options
            if (_logFileName == logFileName && _logLevel == logLevel)
                return;

            // try to parse loglevel
            LogLevel currentLogLevel;
            try { currentLogLevel = LogLevel.FromString (logLevel); }
            catch { currentLogLevel = LogLevel.Info; }

            // save current log configuration
            _logFileName = logFileName;
            _logLevel = currentLogLevel.ToString ();

            // prepare log configuration
            var config = new NLog.Config.LoggingConfiguration ();

            // console output
            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 = logFileName;
            fileTarget.Layout = "${longdate}\t${callsite}\t${level}\t\"${message}${onexception: \t [Exception] ${exception:format=tostring}}\"";
            fileTarget.ConcurrentWrites = true;
			fileTarget.ConcurrentWriteAttemptDelay = 10;
            fileTarget.ConcurrentWriteAttempts = 8;
            fileTarget.AutoFlush = true;
            fileTarget.KeepFileOpen = true;
            fileTarget.DeleteOldFileOnStartup = false;
            fileTarget.ArchiveAboveSize = 4 * 1024 * 1024;  // 4 Mb
            fileTarget.MaxArchiveFiles = 10;
            fileTarget.ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.DateAndSequence;
            fileTarget.ArchiveDateFormat = "yyyyMMdd_HHmmss";

            // set file output to be async (commented out since doesn't work on mono)
            // var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper (fileTarget);

            config.AddTarget ("file", fileTarget);

            // configure log from configuration file
            var rule2 = new NLog.Config.LoggingRule ("*", currentLogLevel, fileTarget);
            config.LoggingRules.Add (rule2);

            // External Log Target
            if (options != null && options.targets != null)
            {
                foreach (var t in options.targets)
                {
                    config.AddTarget (t);
                    config.LoggingRules.Add (new NLog.Config.LoggingRule ("*", currentLogLevel, t));
                }
            }

            // set configuration options
            LogManager.Configuration = config;
        }
Esempio n. 45
0
        public static void Main(string[] args)
        {
            var baseConfigBuilder = new ConfigurationBuilder();
            baseConfigBuilder.SetBasePath(Directory.GetCurrentDirectory());
            baseConfigBuilder.AddCommandLine(args);
            baseConfigBuilder.AddEnvironmentVariables();
            var configFile = baseConfigBuilder.Build()["config"];
            if (string.IsNullOrEmpty(configFile))
            {
                Console.WriteLine("No Config File");
                Console.WriteLine("Need Parameter \"--config path\"");
                return;
            }
            baseConfigBuilder.AddJsonFile(configFile, true, true);
            var baseConfig = baseConfigBuilder.Build();
            var logConfigFile = baseConfig["Data:LogConfig"];
            var notifyAppsConfigFile = baseConfig["Data:NotifyAppsConfig"];
            var appChannelConfigFile = baseConfig["Data:AppChannelConfig"];
            baseConfigBuilder
                .AddJsonFile(logConfigFile, true, true)
                .AddJsonFile(notifyAppsConfigFile, true, true)
                .AddJsonFile(appChannelConfigFile, true, true);
            Configuration = baseConfigBuilder.Build();

            //Nlog
            var nlogConfig = new NLog.Config.LoggingConfiguration();
            BahamutCommon.LoggerLoaderHelper.LoadLoggerToLoggingConfig(nlogConfig, Configuration, "Logger:fileLoggers");

            #if DEBUG
            BahamutCommon.LoggerLoaderHelper.AddConsoleLoggerToLogginConfig(nlogConfig);
            #endif
            LogManager.Configuration = nlogConfig;

            try
            {
                //CSServer
                var server = new ChicagoServer();
                Server = server;
                server.UseNetConfig(new NetConfigReader());
                server.UseServerConfig(new ServerConfigReader());
                server.UseLogger(new FileLogger(Configuration["ServerLog"]));
            #if DEBUG
                server.UseLogger(ConsoleLogger.Instance);
            #endif
                server.UseMessageRoute(new JsonRouteFilter());
                server.UseExtension(new BahamutUserValidationExtension());
                server.UseExtension(new SharelinkerValidateExtension());
                server.UseExtension(new BahamutAppValidateExtension());

                //NotificationCenter Extension
                var notificationExt = new NotificaionCenterExtension();
                server.UseExtension(notificationExt);
                server.UseExtension(new HeartBeatExtension());
                server.StartServer();
            #if DEBUG
                DebugConsole();
            #else
                Thread.Sleep(Timeout.Infinite);
            #endif
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("Chicago").Fatal(ex);
                throw;
            }
        }
Esempio n. 46
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;
        }
        /// <summary>
        /// Log initialization.
        /// </summary>
        internal static void InitializeLog (string logFileName = null, string logLevel = null, InitializationOptions initOptions = null, FlexibleOptions appOptions = null)
        {
            // default parameters initialization from config file
            if (String.IsNullOrEmpty (logFileName))
                logFileName = _logFileName ?? System.Configuration.ConfigurationManager.AppSettings["logFilename"];
			if (String.IsNullOrEmpty (logFileName))
                logFileName = ("${basedir}/log/" + typeof (ConsoleUtils).Namespace.Replace (".SimpleHelpers", "") + ".log");
            if (String.IsNullOrEmpty (logLevel))
                logLevel = _logLevel ?? (System.Configuration.ConfigurationManager.AppSettings["logLevel"] ?? "Info");

            // check if log was initialized with same options
            if (_logFileName == logFileName && _logLevel == logLevel)
                return;

            // try to parse loglevel
            LogLevel currentLogLevel;
            try { currentLogLevel = LogLevel.FromString (logLevel); }
            catch { currentLogLevel = LogLevel.Info; }

            // save current log configuration
            _logFileName = logFileName;
            _logLevel = currentLogLevel.ToString ();

            // check initialization options
            var localOptions = initOptions != null ? initOptions.Clone () : new InitializationOptions ();
            // adjust options based on arguments
            if (appOptions != null)
            {
                if (!localOptions.DisableLogFile.HasValue && appOptions.HasOption ("DisableLogFile"))
                    localOptions.DisableLogFile = appOptions.Get ("DisableLogFile", false);
                if (localOptions.EnableLogTargets == null && !String.IsNullOrEmpty (appOptions.Get ("EnableLogTargets")))
                    localOptions.EnableLogTargets = appOptions.GetAsList ("EnableLogTargets").Where (i => !String.IsNullOrWhiteSpace (i)).Select (i => i.Trim ()).ToArray ();
                if (localOptions.DisableLogTargets == null && !String.IsNullOrEmpty (appOptions.Get ("DisableLogTargets")))
                    localOptions.DisableLogTargets = appOptions.GetAsList ("DisableLogTargets").Where (i => !String.IsNullOrWhiteSpace (i)).Select (i => i.Trim ()).ToArray ();
            }

            // prepare list of enabled targets
            HashSet<string> enabledTargets;
            // if enabled log targets was provided, use it!
            if (localOptions.EnableLogTargets != null && localOptions.EnableLogTargets.Count > 0)
            {
                enabledTargets = new HashSet<string> (localOptions.EnableLogTargets, StringComparer.OrdinalIgnoreCase);
            }
            // else we remove disabled target...
            else
            {
                enabledTargets = new HashSet<string> (StringComparer.OrdinalIgnoreCase) { "console", "file" };
                // set enabled targets
                if (localOptions.Targets != null)
                {
                    foreach (var i in localOptions.Targets)
                    {
                        foreach (var n in GetNLogTargetName (i))
                            enabledTargets.Add (n);
                    }
                }
                // remove disabled targets
                if (localOptions.DisableLogTargets != null)
                    foreach (var i in localOptions.DisableLogTargets)
                        enabledTargets.Remove (i);
                if (localOptions.DisableLogFile ?? false)
                    enabledTargets.Remove ("file");                
            }

            // prepare log configuration
            var config = new NLog.Config.LoggingConfiguration ();

            // console output
            if (!Console.IsOutputRedirected && enabledTargets.Contains ("console"))
            {
                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
            if (enabledTargets.Contains ("file"))
            {
                var fileTarget = new NLog.Targets.FileTarget ();
                fileTarget.FileName = logFileName;
                fileTarget.Layout = "${longdate}\t${callsite}\t${level}\t\"${message}${onexception: \t [Exception] ${exception:format=tostring}}\"";
                fileTarget.ConcurrentWrites = true;
                fileTarget.ConcurrentWriteAttemptDelay = 10;
                fileTarget.ConcurrentWriteAttempts = 8;
                fileTarget.AutoFlush = true;
                fileTarget.KeepFileOpen = true;
                fileTarget.DeleteOldFileOnStartup = false;
                fileTarget.ArchiveAboveSize = (localOptions.MaxLogFileSize > 0) ? localOptions.MaxLogFileSize : 4 * 1024 * 1024;  // 4 Mb
                fileTarget.MaxArchiveFiles = (localOptions.MaxArchiveLogFiles > 0) ? localOptions.MaxArchiveLogFiles : 10;
                fileTarget.ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.DateAndSequence;
                fileTarget.ArchiveDateFormat = "yyyyMMdd";
                fileTarget.ArchiveFileName = System.IO.Path.ChangeExtension (logFileName, ".{#}" + System.IO.Path.GetExtension (logFileName));

                // set file output to be async (commented out since doesn't work well on mono)
                // var wrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper (fileTarget);

                config.AddTarget ("file", fileTarget);

                // configure log from configuration file
                var rule2 = new NLog.Config.LoggingRule ("*", currentLogLevel, fileTarget);
                config.LoggingRules.Add (rule2);
            }

            // External Log Target
            if (localOptions.Targets != null)
            {
                foreach (var t in localOptions.Targets)
                {
                    if (GetNLogTargetName (t).Any (i => enabledTargets.Contains (i)))
                    {
                        config.AddTarget (t);
                        config.LoggingRules.Add (new NLog.Config.LoggingRule ("*", currentLogLevel, t));
                    }
                }
            }

            // set configuration options
            LogManager.Configuration = config;
        }
        public void TestExecuteExperimentLogs()
        {
            var target = new MockLogTarget();
            var logConfig = new NLog.Config.LoggingConfiguration();
            logConfig.AddTarget("MockLogger", target);
            NLog.LogManager.Configuration = logConfig;

            MockProgress progress = new MockProgress();

            Experiment experiment = LoadExperiment("basic_graph.teml");

            using (var dispatcher = ExperimentRunnerHelper.CreateExperimentRunner(experiment, AppContext.WorkspaceInstance, AppContext.Components))
            {
                dispatcher.ExecuteExperiment(progress);
            }
            // only two nodes log, because the other two are start/end
            Assert.AreEqual(2, target.NumEvents); 
        }
Esempio n. 49
0
        protected override void Configure(TestConfiguration config, Random random)
        {
            base.Configure(config, random);

            var c = new NLog.Config.LoggingConfiguration();
            var traceTarget = new NLog.Targets.TraceTarget();
            traceTarget.Layout = "${message}";
            c.AddTarget("trace", traceTarget);

            var rule1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Error, traceTarget);
            c.LoggingRules.Add(rule1);

            NLog.LogManager.Configuration = c;

            Logger =  NLog.LogManager.GetCurrentClassLogger();
        }