コード例 #1
2
ファイル: Program.cs プロジェクト: modulexcite/FieldLog
        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();
        }
コード例 #2
0
        private static Logger SetupLog(int jobNumber)
        {
            var loggerName = $"Job{jobNumber}";
            //create a custom target per job
            var target = new NLog.Targets.FileTarget()
            {
                FileName = $"Arquivo{jobNumber}.Log",
                Name     = $"logfile{jobNumber}",
                Layout   = "${logger} ${longdate} ${level} ${message}",
            };

            //add the target to the configuration
            lock (LoggerSynchronization) //avoid concurrency issues between the jobs
            {
                //check if configuration exists
                if (NLog.LogManager.Configuration == null)
                {
                    NLog.LogManager.Configuration = new LoggingConfiguration();
                }
                var config = NLog.LogManager.Configuration;
                config.AddTarget(target);
                config.AddRuleForAllLevels(target, loggerName);
                NLog.LogManager.ReconfigExistingLoggers();
            }
            return(NLog.LogManager.GetLogger(loggerName));
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: quarck/RssMonitorBot
        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;
        }
コード例 #4
0
        // ^


        // NLOG
        public void ImplementLogging()
        {
            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
            NLog.LogManager.Configuration = config;

            NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                Logger.Info("Hello world");
                System.Console.ReadKey();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Goodbye cruel world");
            }
        }
コード例 #5
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;
        }
コード例 #6
0
        /// <summary>
        /// Creates a logger for a class
        /// </summary>
        /// <param name="debug"></param>
        /// <returns></returns>
        public NLog.Logger InitLogger(bool debug)
        {
            var config = new NLog.Config.LoggingConfiguration();

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

            // Rules for mapping loggers to targets
            if (debug)
            {
                config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);
            }
            else
            {
                config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile);
            }


            // Apply config
            NLog.LogManager.Configuration = config;
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
            return(logger);
        }
コード例 #7
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;
        }
コード例 #8
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;
        }
コード例 #9
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();
        }
コード例 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CityInfoContext cityInfoContext)
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "nlog-${shortdate}.log"
            };

            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            //loggerFactory.AddProvider(new NLog.Extensions.Logging.NLogLoggerProvider());
            loggerFactory.AddNLog();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
            }

            cityInfoContext.EnsureSeedDataForcontext();

            app.UseStatusCodePages();

            app.UseMvc();


            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
コード例 #11
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());
            }
        }
コード例 #12
0
        private static LogFactory BuildLogFactory2()
        {
            LogFactory logFactory = new LogFactory();

            var config = new LoggingConfiguration();

            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = @"[${date:format=HH\:mm\:ss | fff}ms | Id ${pad:padding=3:inner=#${logger}} | ${pad:padding=5:inner=#${level:uppercase=true}}] : ${message}${when:when=length('${exception}')>0:Inner= | EXCEPTION}",
            };
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                Layout       = @"[${date:format=yyyy-MM-dd HH\:mm\:ss | fff}ms | ${pad:padding=3:inner=#${logger:format=00}} | ${pad:padding=6:inner=#${level:uppercase=true}}] : ${message}${when:when=length('${exception}')>0:inner=${exception:format=tostring}:}",
                FileName     = "file.txt",
                FileNameKind = NLog.Targets.FilePathKind.Relative,
            };
            var logsentinel = new NLog.Targets.NLogViewerTarget("logsentinel")
            {
                IncludeSourceInfo = true,
                Address           = "tcp://127.0.0.1:9999",
                Layout            = logfile.Layout,
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logsentinel);

            logFactory.Configuration = config;
            return(logFactory);
        }
コード例 #13
0
        // ModLoader Injection
        public static void InitMod()
        {
            var caller = Assembly.GetEntryAssembly()?.GetName().Name;
            var server = caller != null && caller.Equals("TerrariaServer");

            if (caller == null || server)
            {
                return;
            }

            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName                = $"{AssemblyDirectory}/logs/client.log",
                MaxArchiveFiles         = 10,
                Layout                  = Layout.FromString("${longdate}|${level:uppercase=true}|${logger}|${threadid}|${message}|${exception:format=tostring}"),
                ArchiveOldFileOnStartup = true
            };

            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);
            LogManager.Configuration = config;

            try
            {
                Main.OnEnginePreload += () =>
                {
                    var myMod = new MyMod(LogManager.GetLogger("StreamIntegration"));
                };
            }
            catch (Exception e)
            {
                var logger = LogManager.GetCurrentClassLogger();
                logger.Error(e, "Error loading mod");
            }
        }
コード例 #14
0
ファイル: Logger.cs プロジェクト: yj26141780712/FytSoa3.1
 /// <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;
     }
 }
コード例 #15
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>());
        }
コード例 #16
0
ファイル: Startup.cs プロジェクト: Sharelink/Wellington
        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!");
        }
コード例 #17
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();    //启动时检查更新
        }
コード例 #18
0
        static void Main(string[] args)
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logFile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "log.txt"
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logConsole");

            NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFile);
            NLog.LogManager.Configuration = config;

            IFileHandler fileHandler = new TxtFileHandler("Persons.txt");

            try
            {
                Person[] persons = fileHandler.ReadData();
                foreach (var person in persons)
                {
                    Console.WriteLine($"{person.FirstName} - {person.LastName} of age: {person.Age}");
                }

                FunStatistics stats = new FunStatistics();
                stats.CrunchTheNumbers(persons);
                Console.WriteLine($"Most found letter in the names: {stats.MostFoundLetter()}");
                stats.PrinAll();
            }
            catch (MyCustomException ex)
            {
                log.Error($"Exception message: {ex.Message}, Stacktrace: {ex.StackTrace}, ");
            }
        }
コード例 #19
0
ファイル: LoggerProvider.cs プロジェクト: mikeqa1987/HomeATF
        public static ILogger GetLogger(ISettings settings)
        {
            var configuration = new LoggingConfiguration();

            var fileTarget = new NLog.Targets.FileTarget("file")
            {
                FileName = settings.LogFilePath,
                Layout   = @"${longdate} ${uppercase: ${level}} ${message}",
            };

            var debugTarget = new NLog.Targets.DebuggerTarget("debug")
            {
                Layout = @"${uppercase: ${level}} ${message}",
            };

            configuration.AddTarget(fileTarget);
            configuration.AddTarget(debugTarget);

            configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);
            configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, debugTarget);
            LogManager.Configuration = configuration;

            var logger = LogManager.GetCurrentClassLogger();

            logger.Info("----------------------New Log Started--------------------------");
            logger.Info($"Started logging to {settings.LogFilePath} at {DateTime.Now}");

            return(logger);
        }
コード例 #20
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();
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: maxbyz/Server
        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();
            }
        }
コード例 #22
0
        private static void Main(string[] args)
        {
            if (!File.Exists("config.json"))
            {
                Console.WriteLine("Couldn't find config.json. Please create it");
                return;
            }

            NLog.Config.ConfigurationItemFactory.Default.Targets.RegisterDefinition("DiscordChannel", typeof(DiscordChannelTarget));

            var config  = new NLog.Config.LoggingConfiguration();
            var logFile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "output.log"
            };
            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;

            var json    = File.ReadAllText("config.json");
            var options = JsonConvert.DeserializeObject <Options>(json);

            DiscordBot = new Bot();
            DiscordBot.RunAsync(options).GetAwaiter().GetResult();
        }
コード例 #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);
        }
コード例 #24
0
        private static void EnsureFactoryCreated()
        {
            if (factory == null)
            {
                var config        = new LoggingConfiguration();
                var dir           = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Logging)).Location);
                var dirPath       = Path.Combine(dir, "Logging");
                var logFileTarget = new NLog.Targets.FileTarget()
                {
                    CreateDirs              = true,
                    FileName                = Path.Combine(dirPath, "dicom-viewer.log"),
                    FileNameKind            = NLog.Targets.FilePathKind.Absolute,
                    Layout                  = "${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}",
                    Name                    = "FileLog",
                    ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.DateAndSequence,
                    MaxArchiveFiles         = 10,
                    ArchiveOldFileOnStartup = true
                };
                config.AddTarget(logFileTarget);
                config.AddRuleForAllLevels(logFileTarget, "*", false);

                factory = LoggerFactory.Create(builder =>
                {
                    builder
                    .AddFilter("Microsoft", LogLevel.Warning)
                    .AddFilter("System", LogLevel.Warning)
                    .AddFilter("DicomViewer", LogLevel.Debug)
                    .AddNLog(config)
                    .AddConsole();
                });
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: eklnc/serilogVSnlog
        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);
        }
コード例 #26
0
        /// <summary>
        /// https://code-maze.com/net-core-web-development-part3/
        /// Used https://stackoverflow.com/questions/61553415/using-nlog-console-logging-together-in-net-core-console-app
        /// </summary>
        /// <param name="services"></param>
        public void SetupServices(IServiceCollection services)
        {
            services.AddTransient <ILoggerManager, LoggerManager>();

            var config = new LoggingConfiguration();

            if (File)
            {
                var logfile = new NLog.Targets.FileTarget("logfile")
                {
                    FileName = "log.txt"
                };
                config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            }

            if (Console)
            {
                var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
                config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            }

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

            var logger = LogManager.GetCurrentClassLogger();

            logger.Info($"Completed Setup of NLog");
        }
コード例 #27
0
        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);
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: Lokixa/SchoolAutomation
        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();
        }
コード例 #29
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;
     }
 }
コード例 #30
0
        private string SetupTestDir(string testName)
        {
            //Setup directory for unit test
            string dir = MainTestDir() + TestFolder() + testName + Path.DirectorySeparatorChar;

            if (Directory.Exists(dir))
            {
                var d = new DirectoryInfo(dir);
                d.Delete(true);
            }
            Directory.CreateDirectory(dir);

            //setup the test log file
            var rootDir = RootDir();

            //var s = System.IO.GGetCurrentDirectory()
            LogManager.Configuration = new XmlLoggingConfiguration(rootDir + Path.DirectorySeparatorChar + "NLog.config");
            var config  = LogManager.Configuration;
            var logfile = new NLog.Targets.FileTarget(debugLogger)
            {
                FileName = MainTestDir() + TestFolder() + debugLogger + ".txt",
                Layout   = "${message}",
                //DeleteOldFileOnStartup = true,
                KeepFileOpen         = true,
                OpenFileCacheTimeout = 120,
                ConcurrentWrites     = true,
                Name = debugLogger
            };

            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile, debugLogger);
            NLog.LogManager.Configuration = config;

            return(dir);
        }
コード例 #31
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);
        }
コード例 #32
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;
        }
コード例 #33
0
ファイル: FileLogger.cs プロジェクト: Sharelink/Chicago
 public FileLogger(string path)
 {
     var config = LogManager.Configuration == null ? new LoggingConfiguration() : LogManager.Configuration;
     var fileTaget = new NLog.Targets.FileTarget();
     fileTaget.FileName = path;
     fileTaget.Name = "Chicago";
     fileTaget.Layout = "${message};${exception}";
     var logRule = new LoggingRule("Chicago", NLog.LogLevel.Debug, fileTaget);
     config.AddTarget(fileTaget);
     config.LoggingRules.Add(logRule);
     NLog.LogManager.Configuration = config;
 }
コード例 #34
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");
 }
コード例 #35
0
ファイル: BootstrapCommons.cs プロジェクト: Ellos/McManage
        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;
        }
コード例 #36
0
        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>();
        }
コード例 #37
0
        /// <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;
        }
コード例 #38
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;
        }
コード例 #39
0
        static ThisAddIn()
        {
            NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
            NLog.Targets.Target t;
            //System.Diagnostics.Trace.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
            // eg file:///C:/Users/jharrop/Documents/Visual Studio 2010/Projects/com.plutext.search/com.plutext.search.main/bin/Debug/com.plutext.search.main.DLL
            if (System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Contains("Debug"))
            {
                t = new NLog.Targets.DebuggerTarget();
                ((NLog.Targets.DebuggerTarget)t).Layout = "${callsite} ${message}";
            }
            else
            {
                t = new NLog.Targets.FileTarget();
                ((NLog.Targets.FileTarget)t).FileName = System.IO.Path.GetTempPath() + "plutext.txt";
                //// Win 7:  C:\Users\jharrop\AppData\Local\Temp\
                //System.Diagnostics.Trace.WriteLine("TEMP: " + System.IO.Path.GetTempPath());
                ((NLog.Targets.FileTarget)t).AutoFlush = true;
            }
            //ILayout layout = new NLog.Layout("${longdate} ${callsite} ${level} ${message}");
            //NLog.LayoutCollection lc = new NLog.LayoutCollection();
            //lc.Add(layout);
            ////t.GetLayouts().Add(layout);
            //t.PopulateLayouts(lc);

            config.AddTarget("ds", t);
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, t));
            LogManager.Configuration = config;
            log = LogManager.GetLogger("OpenDoPE_Wed");
            log.Info("Logging operational.");
        }
コード例 #40
0
        /// <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;
        }
コード例 #41
0
        private void SetNLOGLoggingToFile()
        {
            //check if file already exists -> new filename

            NLog.Config.LoggingConfiguration config = NLog.LogManager.Configuration;
            //config.

            if (_firstMeasure)
            {
                _logFileTarget = new NLog.Targets.FileTarget();
                _logFileTarget.Name = Logging.TargetNames.FILE;
                _logFileTarget.CreateDirs = true;
                _logFileTarget.KeepFileOpen = true;
                _logFileTarget.Layout = "${message}";
                _logFileTarget.FileName = string.Format("{0}\\{1}.txt", Properties.Settings.Default.NLOG_LOGFILE_LOCATION, Name);
                config.AddTarget(Logging.TargetNames.FILE, _logFileTarget);
                config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, _logFileTarget));
            }
            else
            {
                /*if (Logging.Config.GetTarget(Logging.TargetNames.FILE) != null)
                    config.RemoveTarget(Logging.TargetNames.FILE);*/
                try
                {
                    config.RemoveTarget(Logging.TargetNames.FILE);
                }
                catch (Exception)
                {
                    //throw;
                }
                _logFileTarget.FileName = string.Format("{0}\\{1}.txt", Properties.Settings.Default.NLOG_LOGFILE_LOCATION, Name);
                config.AddTarget(Logging.TargetNames.FILE, _logFileTarget);
            }
            NLog.LogManager.Configuration = config;
        }