Example #1
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();
        }
Example #2
0
        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);
        }
Example #3
0
        /// <summary>
        /// Provides an instance of <see cref="ILogger"/> logging service.
        /// </summary>
        /// <returns>Instance of <see cref="ILogger"/>.</returns>
        public ILogger GetLogger(ISettings settings)
        {
            var config = new LoggingConfiguration();

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

            config.AddTarget(fileTarget);

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

            config.AddTarget(debugTarget);

            config.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, debugTarget);

            LogManager.Configuration = config;

            var logger = LogManager.GetCurrentClassLogger();

            logger.Info("============================ Started new log session ==========================");
            logger.Info("Start time: {time}", DateTime.Now);
            return(logger);
        }
        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("OpenDoPEFriendly");
            log.Info("Logging operational.");
        }
Example #5
0
        public NLogAdapter()
        {
            var config   = new NLog.Config.LoggingConfiguration();
            var logdebug = new NLog.Targets.DebuggerTarget("logdebug");

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logdebug);
            LogManager.Configuration = config;
        }
Example #6
0
        public MiioLogger()
        {
            var logTarget = new NLog.Targets.DebuggerTarget();
            var config    = new NLog.Config.LoggingConfiguration();

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

            _logger = LogManager.GetLogger("MiioEngine");
        }
        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");
        }
Example #8
0
        /// <inheritdoc />
        public virtual void ApplyConfiguration(LoggerOptions options)
        {
            CurrentOptions = options ?? throw new ArgumentNullException(nameof(options), "Null options are not allowed");

            // Validate options
            ValidateOptions(CurrentOptions);

            // Reconfigure NLog
            var fileTarget = new NLog.Targets.FileTarget("FileLog")
            {
                FileName                = options.FileName,
                ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.DateAndSequence,
                ArchiveOldFileOnStartup = options.IsArchiveOnStart,
                Layout = options.LogMessageLayout ?? NLOG_LAYOUT,
                EnableArchiveFileCompression = options.IsCompressed,
                ArchiveAboveSize             = options.SizePerFile.SizeInBytes,
                MaxArchiveFiles = options.ArchiveCount
            };

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

            configuration.AddTarget(fileTarget);

            // Configure rule
            var filter   = string.IsNullOrWhiteSpace(options.Filter) ? "*" : options.Filter;
            var fileRule = new NLog.Config.LoggingRule(filter, options.Level.ToNLog(), fileTarget);

            configuration.LoggingRules.Add(fileRule);

            // Debug
            if (options.LogToDebugStream)
            {
                var debugTarget = new NLog.Targets.DebuggerTarget("DebugLog")
                {
                    Layout = options.LogMessageLayout ?? NLOG_LAYOUT
                };
                configuration.AddTarget(debugTarget);
                var debugRule = new NLog.Config.LoggingRule(filter, options.Level.ToNLog(), debugTarget);
                configuration.LoggingRules.Add(debugRule);
            }

            // Set configuration
            NLog.LogManager.Configuration = configuration;
        }
Example #9
0
        public DebugLogger(string name)
        {
            Logger = LogManager.GetLogger(name);
            Name   = name;
            // ログが出されたときにどういう形式で表示するか決められる マクロは自分で定義できる
            var layout = "${level} ${message} ${frame}";

            // マクロの定義方法 定義名とコールバックの組で宣言できる
            LayoutRenderer.Register("frame", Ondate);
            RichTextBoxTarget target = new RichTextBoxTarget( )
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = layout,
                ToolWindow = false,
                Width      = 600,
                Height     = 600,
            };

            var debugStr = new NLog.Targets.DebuggerTarget(  )
            {
                Layout = layout
            };
            var log4ViewTarget = new NLog.Targets.NetworkTarget() //new NLog.Targets.NLogViewerTarget( )
            {
                Address = "udp://127.0.0.1:7071"
            };

            log4ViewTarget.Layout = "${frame} ";

            var config = new LoggingConfiguration();

            config.AddRule(LogLevel.Info, LogLevel.Fatal, debugStr);
            //config.AddRule( LogLevel.Info , LogLevel.Fatal , target );
            config.AddRule(LogLevel.Info, LogLevel.Fatal, log4ViewTarget);

            LogManager.Configuration = config;

            //var form = target.TargetForm;
            //form.TopMost = true;
            //LoggerForm = form;
        }
Example #10
0
        void ConfigureNLog()
        {
            LogManager.ThrowExceptions = true;

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

            // Targets where to log to: File and Console
            var logconsole = new NLog.Targets.DebuggerTarget("logconsole");
            //var logMethod = new NLog.Targets.MethodCallTarget("logMethod", window.ProcessLog);
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "MS_logfile.txt"
            };

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

            // Apply config
            LogManager.Configuration = config;
        }
        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);
        }
        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.");
        }
Example #13
0
        protected virtual ILogger ConfigureLogging()
        {
            var entryPointAssembly = Assembly.GetEntryAssembly();

            if (entryPointAssembly == null)
            {
                Kernel.Bind <ILoggerFactory>().To <NullLoggerFactory>().InSingletonScope();
                Kernel.Bind <ILogger>().ToConstant(NullLogger.Instance);
                return(NullLogger.Instance);
            }

            var versionAttribute     = entryPointAssembly.GetCustomAttribute <AssemblyVersionAttribute>();
            var infoVersionAttribute = entryPointAssembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>();

            string version = versionAttribute?.Version ?? infoVersionAttribute?.InformationalVersion ?? "Unknown";

            var appFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                entryPointAssembly.GetName().Name,
                version);

            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }

#pragma warning disable CA2000 // Dispose objects before losing scope (will be disposed by kernel)

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

#if DEBUG
            var debugConsoleTarget = new NLog.Targets.DebuggerTarget("debuggerTarget");
            nlogConfig.AddTarget(debugConsoleTarget);
            nlogConfig.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, debugConsoleTarget);
#endif

            var logFileTarget = new NLog.Targets.FileTarget("logfileTarget")
            {
                FileName = Path.Combine(appFolder, "log.txt")
            };
            nlogConfig.AddTarget(logFileTarget);
            nlogConfig.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logFileTarget);

            var loggerFactory = LoggerFactory.Create(builder =>
            {
#if DEBUG
                builder.SetMinimumLevel(LogLevel.Trace);
#else
                builder.SetMinimumLevel(LogLevel.Information);
#endif
                builder
                .AddDebug()
                .AddNLog(nlogConfig);
            });
#pragma warning restore CA2000 // Dispose objects before losing scope

            Kernel.Bind <ILoggerFactory>().ToConstant(loggerFactory).InSingletonScope();
            Kernel.Bind <ILogger>().ToMethod(context =>
            {
                var factory      = context.Kernel.Get <ILoggerFactory>();
                var categoryName = context.Request?.ParentRequest?.Service.FullName ?? "Uncategorized";
                return(factory.CreateLogger(categoryName));
            });

            return(loggerFactory.CreateLogger(GetType().FullName));
        }
        private static void Main(string[] args)
        {
            // Configure NLog.
            var config     = new NLog.Config.LoggingConfiguration();
            var logconsole = new NLog.Targets.ColoredConsoleTarget("console");
            var logdebug   = new NLog.Targets.DebuggerTarget("debugger");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, logdebug);
            LogManager.Configuration = config;

            ILogger _log = LogManager.GetCurrentClassLogger();

            var channelOptions = new ChannelConnectionOptions();

            channelOptions.SetHostname("172.16.0.2");

            DeviceFactory.Initialize("homie");

            // Consumers can share a single connection to the broker.
            var _clientConnection = new YahiTevuxClientConnection();

            _clientConnection.Initialize(channelOptions);
            _clientConnection.Connect();

            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Creating AirConditionerConsumer ==========================");
            _log.Info("====================================================================");
            var airConditionerConsumer = new AirConditionerConsumer();

            airConditionerConsumer.Initialize(_clientConnection);

            Thread.Sleep(2000);
            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Creating AirConditionerProducer ==========================");
            _log.Info("====================================================================");
            var airConditionerProducer = new AirConditionerProducer();

            airConditionerProducer.Initialize(channelOptions);

            Thread.Sleep(2000);
            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Creating LightbulbConsumer ===============================");
            _log.Info("====================================================================");
            var lightbulbConsumer = new LightbulbConsumer();

            lightbulbConsumer.Initialize(_clientConnection);

            Thread.Sleep(2000);
            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Creating LightbulbProducer ===============================");
            _log.Info("====================================================================");
            var lightbulbProducer = new LightbulbProducer();

            lightbulbProducer.Initialize(channelOptions);

            Thread.Sleep(2000);
            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Parsing Homie tree for problems ==========================");
            _log.Info("====================================================================");
            // Note that Eclipse Mosquitto broker can transmit ~100 retained messages by default. Set max_queue_messages to 0 in mosquito.conf to remove this limit,
            // or otherwise parser will have a lot of problems.
            var homieFecther = new HomieTopicFetcher();

            homieFecther.Initialize(channelOptions);
            homieFecther.FetchDevices(DeviceFactory.BaseTopic, out var topicDump2);
            var homieTree = HomieTopicTreeParser.Parse(topicDump2, DeviceFactory.BaseTopic, out var errorList, out var warningList);

            if (errorList.Length + warningList.Length == 0)
            {
                _log.Info("TreeParser:tree looks ok.");
            }
            else
            {
                foreach (var problem in errorList)
                {
                    _log.Error("TreeParser:" + problem);
                }
                foreach (var problem in warningList)
                {
                    _log.Warn("TreeParser:" + problem);
                }
            }


            Thread.Sleep(2000);
            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Creating DynamicConsumer =================================");
            _log.Info("====================================================================");
            if (homieTree.Length == 0)
            {
                _log.Error("DynamicConsumer:no devices in the tree :(");
            }
            else
            {
                var dynamicConsumer = new DynamicConsumer();
                dynamicConsumer.Initialize(_clientConnection, homieTree[0]);
            }

            _log.Info("");
            _log.Info("====================================================================");
            _log.Info("========= Initialization complete ==================================");
            _log.Info("====================================================================");
            Console.ReadLine();
        }