Example #1
0
        private static void ConfigureLogging(IConfiguration config)
        {
            var logConfiguration = new LogConfiguration();

            config.GetSection("common:logging").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);
        }
Example #2
0
        public void ReadFileWithFlags()
        {
            // Arrange
            string logCfgFn = Path.Combine(TestContext.CurrentContext.TestDirectory, "_utlog2.cfg");

            // Act
            LogConfiguration lgCfg = ConfigurationReader.ReadFile(logCfgFn, false);

            // Assert
            Assert.IsNotNull(lgCfg);
            Assert.AreEqual(ELogLevel.Debug, lgCfg.Level);
            Assert.AreEqual("%date %level %text%nl", lgCfg.Pattern);

            Assert.AreEqual(2, lgCfg.Streams.Length);

            ILogStream consoleStream = lgCfg.Streams[0];

            Assert.AreEqual(typeof(ConsoleStream), consoleStream.GetType());

            ILogStream fileStream = lgCfg.Streams[1];

            Assert.AreEqual(typeof(FileStream), fileStream.GetType());
            Assert.AreEqual("_lfc2.txt", ((FileStream)fileStream).FileName);
            Assert.AreEqual(true, ((FileStream)fileStream).Append);
            Assert.AreEqual(ELockingModel.Minimal, ((FileStream)fileStream).LockingModel);
        }
Example #3
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "services/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });

            config.EnableQuerySupport();
            config.Services.Replace(typeof(ITraceWriter), new ServiceTracer());
            config.Formatters.Add(new SyndicationFeedFormatter());

            var logConfig = new LogConfiguration();
        }
Example #4
0
        public void ReadWithArguments()
        {
            // Arrange
            string logCfgFn = Path.Combine(TestContext.CurrentContext.TestDirectory, "_utlog3.cfg");

            // Act
            LogConfiguration lgCfg = ConfigurationReader.ReadFile(logCfgFn, false);

            // Assert
            Assert.IsNotNull(lgCfg);
            Assert.AreEqual(ELogLevel.Debug, lgCfg.Level);
            Assert.AreEqual("%date(dd.MM.yyyy HH:mm:ss:fff) %level %text%nl", lgCfg.Pattern);

            Assert.AreEqual(3, lgCfg.Streams.Length);

            ILogStream debugStream = lgCfg.Streams[0];

            Assert.AreEqual(typeof(DebugStream), debugStream.GetType());

            ILogStream consoleStream = lgCfg.Streams[1];

            Assert.AreEqual(typeof(ConsoleStream), consoleStream.GetType());

            ILogStream fileStream = lgCfg.Streams[2];

            Assert.AreEqual(typeof(FileStream), fileStream.GetType());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMvc(options =>
            {
                options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
                options.InputFormatters.Add(new PlainTextInputFormatter());
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            });

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new Info {
                    Title = "Hein.RulesEngine.API"
                });
                x.DescribeAllEnumsAsStrings();
            });

            //TODO put this into appsettings.json
            var logConfig = new LogConfiguration()
            {
                SystemName    = "Hein.RulesEngine.API",
                Environment   = "Test",
                EnabledLevels = new string[] { "Debug", "Info", "Warn", "Error" }
            };

            services.AddSingleton <ILogProvider>(s => new ConsoleLogProvider(logConfig));


            services.AddTransient <IRepositoryContext>(s => new RepositoryContext(RegionEndpoint.USEast2));
            services.AddTransient <IAdminToEngineCodeConversion>(s => new AdminToEngineCodeConversion(new CodeConversionProvider(new ApiService())));

            services.BuildServiceLocator();
        }
        public SerilogLogMethod(LogConfiguration config)
        {
            var loggerConfig = new LoggerConfiguration();

            var(_, (console, file, elasticSearch, tracing)) = config;

            if (console.Enabled != null && console.Enabled.Value)
            {
                loggerConfig.WriteTo.Console(
                    outputTemplate: "{NewLine}{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ---{NewLine}{Message:lj}{NewLine}");
            }

            if (file.Enabled != null && file.Enabled.Value)
            {
                loggerConfig.WriteTo.File(
                    file.Path,
                    rollingInterval: Day,
                    outputTemplate: "{Message}{NewLine}");
            }

            if (elasticSearch.Enabled != null && elasticSearch.Enabled.Value)
            {
                loggerConfig.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticSearch.Uri))
                {
                    AutoRegisterTemplate = true,
                });
            }

            if (tracing.Enabled != null && tracing.Enabled.Value)
            {
                loggerConfig.WriteTo.OpenTracing();
            }

            this.logger = loggerConfig.CreateLogger();
        }
Example #7
0
        private Logger GetDefaultLogger()
        {
            var serviceConfig   = ServiceConfigurationLoader.Load();
            var adapterSettings = LogConfiguration.CreateLogAdapterSetting(serviceConfig.Raw);

            return(new Logger(Context.Request.RawUrl, adapterSettings));
        }
Example #8
0
        public void LogConfig2Test()
        {
            LogConfiguration logConfiguration = new LogConfiguration();

            logConfiguration.BasePath = "c:\\";
            FileLoggerFactory factory = new FileLoggerFactory(new FileLoggerProvider(logConfiguration));
            ILogger           logger  = factory.Create("Test.log");

            Assert.AreEqual(logger.FileName, "Test.log");
            Console.WriteLine(logger.DirectoryName);
            Console.WriteLine(logger.FileName);
            Assert.AreEqual(logger.DirectoryName, Path.Combine(logConfiguration.BasePath, "Logs\\"));
            logger.Configuration = new LogConfiguration()
            {
                BasePath = "D:\\"
            };
            Console.WriteLine(logger.DirectoryName);
            Assert.AreEqual(logger.DirectoryName, "D:\\Logs\\");
            ILogger logger1 = factory.Create("Test2.log");

            Assert.AreEqual(logger1.FileName, "Test2.log");
            Console.WriteLine(logger1.DirectoryName);
            Console.WriteLine(logger1.FileName);
            Assert.AreEqual(logger1.DirectoryName, Path.Combine(logConfiguration.BasePath, "Logs\\"));
        }
Example #9
0
        private void Initialize(string path, IPrincipal user)
        {
            ServiceContainer = GlobalContainer.CreateChild();

            this.Id   = Guid.NewGuid();
            this.User = user;

            var info = PathInfoBuilder.Build(path);

            if (info == null)
            {
                return;
            }
            this.ServiceUnitName = info.ServiceUnitName;
            this.Version         = info.Version;
            this.Role            = info.Role;
            this.Request         = new ServiceUnitRequest(this, info);
            this.Configuration   = ServiceConfigurationLoader.Load(info.ServiceUnitName, info.Version, info.Role);

            var logConfig = LogConfiguration.CreateLogAdapterSetting(this.Configuration.Raw);

            var       logger   = new Logger(info.ProcessPath, logConfig);
            IIdentity identity = (this.User != null) ? this.User.Identity : new GenericIdentity("Anonymous");

            this.LogContext = new LogContext(logger, this.Id, identity);

            ServiceContainer.AddInstance(this);
            ServiceContainer.AddInstance(this.LogContext);
            ServiceContainer.AddInstance(this.Configuration);
        }
Example #10
0
        private async void ReloadConfiguration(bool delay = false)
        {
            if (_isReloading)
            {
                return;
            }

            try
            {
                _isReloading = true;

                // Wait some time IO from other processes to complete
                if (delay)
                {
                    await Task.Delay(100);
                }

                if (Directory.Exists(ConfigurationRoot) == false)
                {
                    return;
                }

                LogConfiguration = new LogConfiguration(ConfigurationRoot, _loggerFactory.CreateLogger <LogConfiguration>());
            }
            finally
            {
                _isReloading = false;
            }
        }
Example #11
0
        protected virtual StringBuilder FormatPrefix(
            LogConfiguration configuration,
            LogLevel logLevel,
            DateTime dateTime,
            StringBuilder builder = null
            )
        {
            if (builder == null)
            {
                builder = new StringBuilder();
            }

            if (!string.IsNullOrWhiteSpace(TimestampFormat))
            {
                builder.Append(dateTime.ToString(TimestampFormat));
                builder.Append(' ');
            }

            builder.Append($"[{logLevel}]");
            builder.Append(' ');

            // ReSharper disable once InvertIf
            if (!string.IsNullOrEmpty(configuration.Tag))
            {
                builder.Append(configuration.Tag);
                builder.Append(": ");
            }

            return(builder);
        }
Example #12
0
        static void Main(string[] args)
        {
            // Load configuration
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            // Setup logger
            var logConfiguration = new LogConfiguration();

            configuration.GetSection("LogConfiguration").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);

            using (IMessageBus messageBus = CreateMessageBus(configuration))
            {
                var addTask      = Task.Factory.StartNew(() => AddLoop(messageBus), TaskCreationOptions.LongRunning);
                var multiplyTask = Task.Factory.StartNew(() => MultiplyLoop(messageBus), TaskCreationOptions.LongRunning);

                Console.WriteLine("Press any key to stop...");
                Console.ReadKey();

                _stop = true;
                Task.WaitAll(addTask, multiplyTask);
            }
        }
        private string FormatPrefix([NotNull] LogConfiguration configuration, LogLevel logLevel, DateTime dateTime)
        {
            var builder = new StringBuilder();

            if (!configuration.Pretty)
            {
                if (!string.IsNullOrWhiteSpace(TimestampFormat))
                {
                    builder.Append(dateTime.ToString(TimestampFormat));
                    builder.Append(' ');
                }

                builder.Append($"[{logLevel}]");
                builder.Append(' ');
            }

            // ReSharper disable once InvertIf
            if (!string.IsNullOrEmpty(configuration.Tag))
            {
                builder.Append(configuration.Tag);
                builder.Append(": ");
            }

            return(builder.ToString());
        }
        public void ConstructorValidation()
        {
            var validLogConfigs = new[] { new LogConfiguration(null, LogType.Console, LogManager.DefaultSubscriptions), };

            foreach (var value in Enum.GetValues(typeof(Configuration.AllowEtwLoggingValues)))
            {
                var validValue = (Configuration.AllowEtwLoggingValues)value;
                Assert.DoesNotThrow(() => new Configuration(validLogConfigs, validValue));
            }
            var invalidAllowValue =
                (Configuration.AllowEtwLoggingValues)((int)Configuration.AllowEtwLoggingValues.Enabled + 8675309);

            Assert.Throws <ArgumentOutOfRangeException>(() => new Configuration(validLogConfigs, invalidAllowValue));

            Assert.Throws <ArgumentNullException>(() => new Configuration(null));
            Assert.Throws <ArgumentException>(() => new Configuration(new LogConfiguration[0]));

            var invalidConfig = new LogConfiguration("foo", LogType.Network, LogManager.DefaultSubscriptions);

            Assert.Throws <InvalidConfigurationException>(() => invalidConfig.Validate());
            var invalidLogConfigs = new List <LogConfiguration>(validLogConfigs);

            invalidLogConfigs.Add(invalidConfig);
            Assert.Throws <InvalidConfigurationException>(() => new Configuration(invalidLogConfigs));

            var duplicateLogConfigs = new List <LogConfiguration>(validLogConfigs);

            duplicateLogConfigs.AddRange(validLogConfigs);
            Assert.Throws <InvalidConfigurationException>(() => new Configuration(duplicateLogConfigs));

            var memoryLogs = new[]
            { new LogConfiguration("memory", LogType.MemoryBuffer, LogManager.DefaultSubscriptions), };

            Assert.Throws <InvalidConfigurationException>(() => new Configuration(memoryLogs));
        }
Example #15
0
 public LogParser(IConsoleHandler consoleHandler, ILogFormatMapper logFormatMapper,
                  IOptions <LogConfiguration> logConfiguration)
 {
     _consoleHandler   = consoleHandler;
     _logFormatMapper  = logFormatMapper;
     _logConfiguration = logConfiguration.Value;
 }
        /// <summary>
        /// 指定された構成情報を利用してインスタンスを初期化します。
        /// </summary>
        /// <param name="config">構成情報</param>
        public NLogAdapter(LogConfiguration config)
        {
            this.config = config;
            var nlogConfig = new LoggingConfiguration();

            foreach (var pattern in config.LogSettings)
            {
                if (pattern.Resource.Type == "file")
                {
                    var target = new FileTarget();
                    target.Name         = pattern.Resource.Name;
                    target.Layout       = pattern.Resource.Format;
                    target.FileName     = pattern.Resource.FileName;
                    target.ArchiveEvery = FileArchivePeriod.Day;
                    target.Encoding     = System.Text.Encoding.UTF8;
                    nlogConfig.AddTarget(target.Name, target);
                    nlogConfig.LoggingRules.Add(new LoggingRule(pattern.Resource.Name, GetLogLevel(pattern), target));
                }

                if (pattern.Resource.Type == "db")
                {
                    var target = new DatabaseTarget();
                    target.Name             = pattern.Resource.Name;
                    target.ConnectionString = pattern.Resource.Connection;
                    nlogConfig.AddTarget(target.Name, target);
                    nlogConfig.LoggingRules.Add(new LoggingRule(pattern.Resource.Name, GetLogLevel(pattern), target));
                }
            }

            LogManager.Configuration = nlogConfig;
        }
 public void Initialize()
 {
     LogConfiguration configuration = new LogConfiguration();
     _sink = new TestSink();
     configuration.Sinks.Add(_sink);
     _kernel = new LogKernel(configuration);
 }
        protected void InternalWrite(
            [NotNull] LogConfiguration configuration,
            LogLevel logLevel,
            [CanBeNull] Exception exception,
            [CanBeNull] string format,
            [CanBeNull] params object[] args
            )
        {
            if (LogLevel < logLevel)
            {
                return;
            }

            var writer = Console.Out;

            if (LogLevel < LogLevel.Info)
            {
                writer = Console.Error;
            }

            writer.Write(
                configuration.Formatter.Format(configuration, logLevel, DateTime.UtcNow, exception, format, args)
                );

            writer.Flush();
        }
Example #19
0
        public static void Main()
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            var logConfiguration = new LogConfiguration();

            configuration.GetSection("LogConfiguration").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);

            Log.Info("Starting worker...");
            using (var container = ContainerSetup.Create(configuration))
            {
                // eager load the singleton, so that is starts consuming messages
                var messageBus = container.Resolve <IMessageBus>();
                Log.Info("Worker ready");

                Console.WriteLine("Press enter to stop the application...");
                Console.ReadLine();

                Log.Info("Stopping worker...");
            }
            Log.Info("Worker stopped");
        }
Example #20
0
        static void Main()
        {
            LogConfiguration.SetupLog4net();
            ILog   log         = LogManager.GetLogger(typeof(Program));
            string processname = Process.GetCurrentProcess().ProcessName;

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                using (LoadForm frm = new LoadForm())
                {
                    frm.Show();
                    frm.Refresh();

                    Manager.AppSDK_Init();
                }

                Application.Run(new SelectCourseForm(log));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                log.FatalFormat("Application Finish with Error.Error Message: {0}", ex.Message);
            }
            finally
            {
                foreach (var process in Process.GetProcessesByName(processname))
                {
                    process.Kill();
                }
            }
        }
        public void LogControllerTest()
        {
            const int logsPerFile = 5;
            var       testFolder  = TestingFolder + @"\TextLogTests";

            FileUtility.DeleteFiles(testFolder);
            var logConfiguration = new LogConfiguration()
            {
                Log         = true,
                LogDetail   = true,
                LogFilePath = testFolder,
                LogsPerFile = logsPerFile
            };

            var controller = new LogController(logConfiguration, "LogTest");

            const int todo = 5;

            for (var i = 0; i < 5; i++)
            {
                controller.LogDetail("Detail " + i);
                controller.LogLiteral("Message " + i);
                controller.UpdateProgress(i, todo, "Progress");
            }
            const int expectedCount = ((todo * 3) / logsPerFile) + (((todo * 3) % logsPerFile) > 0 ? 1 : 0);
            var       files         = FileUtility.GetFiles(testFolder);

            Assert.AreEqual(expectedCount, files.Count());
        }
        public void AsyncProxy_LogEntriesAreWrittenToSinks()
        {
            LogConfiguration configuration = new LogConfiguration();
            AsyncProxy asyncProxy = new AsyncProxy();
            ManualResetEvent stoppedEvent = new ManualResetEvent(false);
            TestSink sink = new TestSink(stoppedEvent);
            asyncProxy.Sinks.Add(sink);
            configuration.Sinks.Add(asyncProxy);
            using (LogKernel kernel = new LogKernel(configuration))
            {
                ILogger logger = kernel.GetLogger();
                logger.Write(LogLevel.Information, "A message");

                // Wait for the entry to be written.
                if (!stoppedEvent.WaitOne(TimeSpan.FromSeconds(3)))
                {
                    throw new TimeoutException("Timed out while waiting for entries to be written to sink.");
                }

                // Assert that the entry was written to the sink.
                Assert.IsNotNull(sink.Entry);
                Assert.AreEqual("A message", sink.Entry.Message);
                Assert.AreEqual(1, sink.WrittenEntries);
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                    .Build();

            // Common logging
            LogConfiguration logConfiguration = new LogConfiguration();

            config.GetSection("LogConfiguration").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);

            // Serilog
            var log = new LoggerConfiguration()
                      .ReadFrom.Configuration(config) // Serilog.Settings.Configuration
                      .WriteTo.ColoredConsole()
                                                      //.WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day) // reading from appsetting.json
                      .CreateLogger();

            Log.Logger = log;

            ExtMigrationRunner.Initialize().Process();

            log.Error("Test error message");
            log.Information("test information message");

            log.Information("===================================================================");
        }
Example #24
0
        private static void Main()
        {
            // Load configuration
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            // Setup logger
            var logConfiguration = new LogConfiguration();

            configuration.GetSection("LogConfiguration").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);

            // Local file with secrets
            Secrets.Load(@"..\..\..\..\..\secrets.txt");

            // Create the bus and process messages
            using (var messageBus = CreateMessageBus(configuration))
            {
                var addTask      = Task.Factory.StartNew(() => AddLoop(messageBus), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                var multiplyTask = Task.Factory.StartNew(() => MultiplyLoop(messageBus), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

                Console.WriteLine("Press any key to stop...");
                Console.ReadKey();

                _canRun = false;
                Task.WaitAll(addTask, multiplyTask);
            }
        }
Example #25
0
 public App()
 {
     LogConfiguration.ConfigureSeriLog();
     Log = Serilog.Log.ForContext <App>();
     // For some reason this will not work for exceptions thrown from inside the Views.
     AppDomain.CurrentDomain.UnhandledException += MyHandler;
 }
        public static async Task <ContainerBuilder> UseCacheckVishizhukelNetAndPeghAsync(this ContainerBuilder builder, CacheckWindow cacheckWindow)
        {
            var logConfiguration = new LogConfiguration();
            await builder.UseVishizhukelNetDvinAndPeghAsync(new DummyCsArgumentPrompter(), logConfiguration);

            builder.RegisterType <AverageCalculator>().As <IAverageCalculator>();
            builder.RegisterType <CacheckApplication>().As <CacheckApplication>().As <IGuiAndAppHandler>().As <IDataPresenter>().SingleInstance();
            builder.RegisterType <CacheckApplicationModel>().As <CacheckApplicationModel>().As <ICacheckApplicationModel>().As <IApplicationModel>().As <IBusy>().SingleInstance();
            builder.RegisterType <CacheckGuiAndApplicationSynchronizer>().WithParameter((p, _) => p.ParameterType == typeof(CacheckWindow), (_, _) => cacheckWindow).As <IGuiAndApplicationSynchronizer <ICacheckApplicationModel> >();
            builder.RegisterType <CacheckGuiToApplicationGate>().As <IGuiToApplicationGate>().SingleInstance();
            builder.RegisterInstance <ICalculationLogger>(new CalculationLogger(logConfiguration));
            builder.RegisterType <ClassifiedPosting>().As <IClassifiedPosting>();
            builder.RegisterType <ClassifiedPostingsCalculator>().As <IClassifiedPostingsCalculator>();
            builder.RegisterType <DataCollector>().As <IDataCollector>();
            builder.RegisterType <FormattedClassificationComparer>().As <IFormattedClassificationComparer>();
            builder.RegisterType <MonthlyDeltaCalculator>().As <IMonthlyDeltaCalculator>();
            builder.RegisterType <PostingAggregator>().As <IPostingAggregator>();
            builder.RegisterType <PostingClassificationFormatter>().As <IPostingClassificationFormatter>();
            builder.RegisterType <PostingClassificationMatcher>().As <IPostingClassificationMatcher>();
            builder.RegisterType <PostingCollector>().As <IPostingCollector>();
            builder.RegisterType <SourceFileReader>().As <ISourceFileReader>();
            builder.RegisterType <SummaryCalculator>().As <ISummaryCalculator>();
            builder.RegisterType <TypeItemSum>().As <ITypeItemSum>();
            builder.RegisterType <TypeMonthDelta>().As <ITypeMonthDelta>();
            return(builder);
        }
        public void CanSerialize(LogConfiguration configuration)
        {
            var serializer = new JsonSerializer();
            var json       = configuration.ToString(); // ToString returns the JSON representation itself.

            using (var reader = new StringReader(json))
            {
                using (var jsonReader = new JsonTextReader(reader))
                {
                    var deserialized = serializer.Deserialize <LogConfiguration>(jsonReader);
                    Assert.AreEqual(configuration, deserialized);
                    Assert.AreEqual(configuration.Name, deserialized.Name);
                    Assert.AreEqual(configuration.Type, deserialized.Type);
                    foreach (var sub in configuration.Subscriptions)
                    {
                        Assert.IsTrue(deserialized.Subscriptions.Contains(sub));
                    }
                    foreach (var filter in configuration.Filters)
                    {
                        Assert.IsTrue(deserialized.Filters.Contains(filter));
                    }
                    Assert.AreEqual(configuration.BufferSizeMB, deserialized.BufferSizeMB);
                    Assert.AreEqual(configuration.Directory, deserialized.Directory);
                    Assert.AreEqual(configuration.FilenameTemplate, deserialized.FilenameTemplate);
                    Assert.AreEqual(configuration.TimestampLocal, deserialized.TimestampLocal);
                    Assert.AreEqual(configuration.RotationInterval, deserialized.RotationInterval);
                    Assert.AreEqual(configuration.Hostname, deserialized.Hostname);
                    Assert.AreEqual(configuration.Port, deserialized.Port);
                }
            }
        }
Example #28
0
 static DebugLogger()
 {
     if (LogConfiguration == null)
     {
         LogConfiguration = new LogConfiguration();
     }
 }
Example #29
0
 public DataRpositories(ApplicationDataContainer localSettings, string userName)
 {
     _minderLogger  = LogConfiguration.GetFileLogger();
     _containerName = userName;
     _localSettings = localSettings;
     isLocalDataSet = true;
     _userName      = userName;
 }
        public ResponseLoggerMiddleware(RequestDelegate nextMiddlewareDel, IFactoriesManager factoriesManager)
        {
            this.nextMiddlewareDel = nextMiddlewareDel;

            factoriesManager.GetService <ILogger <ResponseLog> >().TryGetTarget(out responseLogger);

            logConfiguration = new LogConfiguration(typeof(RequestLoggerMiddleware));
        }
        public void Register()
        {
            LogManager.Configuration.AddTarget("DbLogger", this);
            LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, this));

            LogManager.ConfigurationReloaded += (sender, args) => Register();
            LogConfiguration.Reload();
        }
Example #32
0
        public MainWindow()
        {
            InitializeComponent();
            Title = Properties.Resources.General_WindowTitle;

            // Init logging
            LogConfiguration.ConfigureSeriLog();
        }
 public void LogSink_InternalLoggerIsRemovedFromSinkWhenDisposed()
 {
     LogConfiguration configuration = new LogConfiguration();
     StringSink sink = new StringSink { Name = "fake" };
     configuration.Sinks.Add(sink);
     LogKernel kernel = new LogKernel(configuration);
     Assert.IsNotNull(sink.InternalLogger);
     kernel.Dispose();
     Assert.IsNull(sink.InternalLogger);
 }
        public void InternalLogger_InternalLoggerDoNotWriteToTraceListenersIfDisabled()
        {
            LogConfiguration configuration = new LogConfiguration();

            // Redirect the output from the console to a string writer.
            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                // Write something to the internal log and make sure we did not intercept it.
                configuration.InternalLogger.Write(LogLevel.Information, "Hello World");
                Assert.AreEqual(0, scope.Listener.Messages.Count);
            }
        }
Example #35
0
        public static IFeliceInitialization Initialize(LogConfiguration logConfiguration = null)
        {
            if (initialized == false)
            {
                Log.Initialize();
                Log.Framework.InfoFormat("Felice application started");

                Dependency.Initialize();

                initialized = true;
            }

            return new FeliceCore();
        }
        public void InternalLogger_InternalLoggerWritesToTraceListeners()
        {
            LogConfiguration configuration = new LogConfiguration();
            configuration.InternalLogger.Enabled = true;

            // Redirect the output from the console to a string writer.
            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                // Write something to the internal log and make sure we intercepted it.
                configuration.InternalLogger.Write(LogLevel.Information, "Hello World");
                Assert.AreEqual(1, scope.Listener.Messages.Count);
                Assert.AreEqual("[BLACKBOX] Hello World", scope.Listener.Messages[0]);
            }
        }
        public void BufferProxy_RemainingMessagesAreFlushedWhenBufferProxyIsDisposed()
        {
            LogConfiguration configuration = new LogConfiguration();
            BufferProxy proxy = new BufferProxy { BufferSize = 3 };
            TestSink sink = new TestSink();
            proxy.Sinks.Add(sink);
            configuration.Sinks.Add(proxy);
            LogKernel kernel = new LogKernel(configuration);
            ILogger logger = kernel.GetLogger();

            Assert.AreEqual(0, sink.MessagesWritten);
            logger.Write(LogLevel.Information, "Hello World!");
            logger.Write(LogLevel.Information, "Hello World Again!");
            Assert.AreEqual(0, sink.MessagesWritten);
            configuration.Dispose();
            Assert.AreEqual(2, sink.MessagesWritten);
        }
        public void LogSinkProxy_UnhandledExceptionsInLogSinkProxyAreHandledAndWrittenToInternalLogWhenWritingMoreThanOneMessage_LogSinkGotNoName()
        {
            // This test is using the buffer proxy to buffer up messages and
            // indirectly use the LogSink.Write(ILogEntry[]) overload on the sink.

            LogConfiguration configuration = new LogConfiguration();
            configuration.InternalLogger.Enabled = true;
            BufferProxy funnelProxy = new BufferProxy() { BufferSize = 0 };
            funnelProxy.Sinks.Add(new ThrowSink(() => new InvalidOperationException("Hello World!")));
            configuration.Sinks.Add(funnelProxy);
            LogKernel kernel = new LogKernel(configuration);
            ILogger logger = kernel.GetLogger();

            string expected = "[BLACKBOX] An unnamed sink of type 'BlackBox.UnitTests.Tests.LogSinkTests+ThrowSink' threw an exception. Hello World!";
            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                logger.Write(LogLevel.Information, "TestMessage");
                Assert.AreEqual(expected, scope.Listener.Messages[0]);
            }
        }
        public void InternalLogger_InternalLoggerRespectsThresholdLevel()
        {
            LogConfiguration configuration = new LogConfiguration();
            configuration.InternalLogger.Enabled = true;
            configuration.InternalLogger.Threshold = LogLevel.Information;

            // Redirect the output from the console to a string writer.
            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                configuration.InternalLogger.Write(LogLevel.Verbose, "1");
                Assert.AreEqual(0, scope.Listener.Messages.Count);
                configuration.InternalLogger.Write(LogLevel.Debug, "2");
                Assert.AreEqual(0, scope.Listener.Messages.Count);
                configuration.InternalLogger.Write(LogLevel.Information, "3");
                Assert.AreEqual(1, scope.Listener.Messages.Count);
                configuration.InternalLogger.Write(LogLevel.Warning, "4");
                Assert.AreEqual(2, scope.Listener.Messages.Count);
                configuration.InternalLogger.Write(LogLevel.Error, "5");
                Assert.AreEqual(3, scope.Listener.Messages.Count);
                configuration.InternalLogger.Write(LogLevel.Fatal, "6");
                Assert.AreEqual(4, scope.Listener.Messages.Count);
            }
        }
Example #40
0
        public static void Register(HttpConfiguration config)
        {
            // Web API routes

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "services/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });

            config.AddODataQueryFilter();

            config.Services.Replace(typeof(ITraceWriter), new ServiceTracer());
            config.Formatters.Add(new SyndicationFeedFormatter());

            var logConfig = new LogConfiguration();
        }
 public void LogSink_LogSinkNamesCanNotChangeAfterKernelInstantiation()
 {
     LogConfiguration configuration = new LogConfiguration();
     StringSink sink = new StringSink { Name = "fake" };
     sink.Name = "fake2";
     sink.Name = "fake3";
     configuration.Sinks.Add(sink);
     Assert.AreEqual("fake3", sink.Name);
     LogKernel kernel = new LogKernel(configuration);
     sink.Name = "fake4";
 }
        public void LogSink_UnhandledExceptionsInLogSinkAreHandledAndWrittenToInternalLog_LogSinkGotNoName()
        {
            LogConfiguration configuration = new LogConfiguration();
            configuration.InternalLogger.Enabled = true;
            configuration.Sinks.Add(new ThrowSink(() => new InvalidOperationException("Hello World!")));
            LogKernel kernel = new LogKernel(configuration);
            ILogger logger = kernel.GetLogger();

            string expected = "[BLACKBOX] An unnamed sink of type 'BlackBox.UnitTests.Tests.LogSinkTests+ThrowSink' threw an exception. Hello World!";
            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                logger.Write(LogLevel.Information, "TestMessage");
                Assert.AreEqual(expected, scope.Listener.Messages[0]);
            }
        }
 public void InternalLogger_InternalLoggerIsDisabledByDefault()
 {
     LogConfiguration configuration = new LogConfiguration();
     Assert.IsFalse(configuration.InternalLogger.Enabled, "The internal logger should be enabled by default.");
 }
        private static bool ParseLogFilters(XmlNode xmlNode, LogConfiguration config)
        {
            bool clean = true;

            foreach (XmlNode source in xmlNode.SelectNodes(LogFilterTag))
            {
                string filterValue = source.InnerText.Trim();
                if (string.IsNullOrEmpty(filterValue))
                {
                    InternalLogger.Write.InvalidConfiguration("empty/invalid filter value");
                    clean = false;
                    continue;
                }

                if (config.Filters.Contains(filterValue))
                {
                    InternalLogger.Write.InvalidConfiguration("duplicate filter value " + filterValue);
                    clean = false;
                    continue;
                }

                config.Filters.Add(filterValue);
            }

            return clean;
        }
        private static bool ParseLogSources(XmlNode xmlNode, LogConfiguration config)
        {
            bool clean = true;

            foreach (XmlNode source in xmlNode.SelectNodes(SourceTag))
            {
                string sourceName = null;
                Guid sourceProvider = Guid.Empty;
                var sourceLevel = EventLevel.Informational;
                var sourceKeywords = (long)EventKeywords.None;
                foreach (XmlAttribute sourceAttribute in source.Attributes)
                {
                    switch (sourceAttribute.Name.ToLower(CultureInfo.InvariantCulture))
                    {
                    case SourceKeywordsAttribute:
                        // Yes, really. The .NET integer TryParse methods will get PISSED if they see 0x in front of
                        // hex digits. Dumb hack is dumb.
                        string value = sourceAttribute.Value.Trim();
                        if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                        {
                            value = value.Substring(2);
                        }

                        if (!long.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                           out sourceKeywords))
                        {
                            InternalLogger.Write.InvalidConfiguration("invalid keywords value " + sourceAttribute.Value);
                            clean = false;
                        }
                        break;
                    case SourceMinSeverityAttribute:
                        if (!Enum.TryParse(sourceAttribute.Value, true, out sourceLevel))
                        {
                            InternalLogger.Write.InvalidConfiguration("invalid severity value " + sourceAttribute.Value);
                            clean = false;
                        }
                        break;
                    case SourceProviderIDAttribute:
                        if (!Guid.TryParse(sourceAttribute.Value, out sourceProvider))
                        {
                            InternalLogger.Write.InvalidConfiguration("invalid providerID GUID " + sourceAttribute.Value);
                            clean = false;
                        }
                        break;
                    case SourceProviderNameAttribute:
                        sourceName = sourceAttribute.Value.Trim();
                        break;
                    }
                }

                var levels = new LogSourceLevels(sourceLevel, (EventKeywords)sourceKeywords);
                if (sourceProvider != Guid.Empty)
                {
                    config.GuidSources[sourceProvider] = levels;
                }
                else if (!string.IsNullOrEmpty(sourceName))
                {
                    config.NamedSources[sourceName] = levels;
                }
                else
                {
                    InternalLogger.Write.InvalidConfiguration("source has neither name nor guid");
                    clean = false;
                }
            }

            return clean;
        }
Example #46
0
 internal NullLogImplementation(LogConfiguration config)
     : base(config, ExceptionWriter.Default)
 {
 }
Example #47
0
 private static bool IsEnabled(LogConfiguration configuration, LogLevel level)
 {
     return (configuration.Level != LogLevel.None && configuration.Level >= level);
 }
 private static void ApplyConfigForEventSource(LogConfiguration config, IEventLogger logger, EventSource source,
                                               LogSourceLevels levels)
 {
     if (config.HasFeature(LogConfiguration.Features.EventSourceSubscription))
     {
         logger.SubscribeToEvents(source, levels.Level, levels.Keywords);
     }
     else if (config.HasFeature(LogConfiguration.Features.GuidSubscription))
     {
         logger.SubscribeToEvents(source.Guid, levels.Level, levels.Keywords);
     }
 }
 public void InternalLogger_ConfigurationHasInternalLogger()
 {
     LogConfiguration configuration = new LogConfiguration();
     Assert.IsNotNull(configuration.InternalLogger, "The internal logger should not be null.");
 }
        private static bool ParseLogNode(XmlNode xmlNode, LogConfiguration config)
        {
            bool clean = true;
            foreach (XmlAttribute logAttribute in xmlNode.Attributes)
            {
                switch (logAttribute.Name.ToLower(CultureInfo.InvariantCulture))
                {
                case LogBufferSizeAttribute:
                    if (!int.TryParse(logAttribute.Value, out config.BufferSize)
                        || !IsValidFileBufferSize(config.BufferSize))
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid buffer size " + logAttribute.Value);
                        config.BufferSize = DefaultFileBufferSizeMB;
                        clean = false;
                    }
                    break;
                case LogDirectoryAttribute:
                    if (!IsValidDirectory(logAttribute.Value))
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid directory name " + logAttribute.Value);
                        clean = false;
                    }
                    else
                    {
                        config.Directory = logAttribute.Value;
                    }
                    break;
                case LogFilenameTemplateAttribute:
                    if (!FileBackedLogger.IsValidFilenameTemplate(logAttribute.Value))
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid filename template " + logAttribute.Value);
                        clean = false;
                    }
                    else
                    {
                        config.FilenameTemplate = logAttribute.Value;
                    }
                    break;
                case LogTimestampLocal:
                    if (!bool.TryParse(logAttribute.Value, out config.TimestampLocal))
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid timestamplocal value " + logAttribute.Value);
                        config.TimestampLocal = false;
                        clean = false;
                    }
                    break;
                case LogRotationAttribute:
                    if (!int.TryParse(logAttribute.Value, out config.RotationInterval)
                        || !IsValidRotationInterval(config.RotationInterval))
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid rotation interval " + logAttribute.Value);
                        config.RotationInterval = DefaultRotationInterval;
                        clean = false;
                    }
                    break;
                case LogHostnameAttribute:
                    if (Uri.CheckHostName(logAttribute.Value) == UriHostNameType.Unknown)
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid hostname name " + logAttribute.Value);
                        clean = false;
                    }
                    else
                    {
                        config.Hostname = logAttribute.Value;
                    }
                    break;
                case LogPortAttribute:
                    if (!int.TryParse(logAttribute.Value, out config.Port)
                        || config.Port <= 0)
                    {
                        InternalLogger.Write.InvalidConfiguration("invalid port " + logAttribute.Value);
                        config.Port = 80;
                        clean = false;
                    }
                    break;
                }
            }

            clean &= ParseLogSources(xmlNode, config);
            clean &= ParseLogFilters(xmlNode, config);
            return clean;
        }
		void RunUpEndpoint()
		{
			// OMITTED: No empty try-catch
			//try
			//{
				//this.Logger.Debug("1 RunUpEndpoint()");

				// Get configuration settings
				XDocument confDoc = XDocument.Load("SipEndpoint.config");
				this.SetAppLevelConfiguration(confDoc.Root);

				/*  Matching levels between:
				 *  -----------------------------|--------------------------------
				 *   Platform SDK logging levels | SIP Endpoint SDK logging levels
				 *  -----------------------------|--------------------------------
				 *    All = 0                    |       NA
				 *    Debug = 1                  |       4
				 *    Trace = 2                  |       3
				 *    Interaction = 3            |       2
				 *    Standard = 4               |       1
				 *    Alarm = 5                  |       0
				 *    None = 6                   |       NA
				 *  -----------------------------|--------------------------------
				 * 
				 *  SIP Endpoint SDK logging levels
				 *  ===============================
				 *   Fatal = 0
				 *   Error = 1
				 *   Warning = 2
				 *   Info = 3
				 *   Debug = 4
				 */

				if (this.enableLogging)
				{
					// Setup logger
					LogConfiguration logConf = new LogConfiguration();
					logConf.Verbose = VerboseLevel.All;
					logConf.Targets.Trace.IsEnabled = true;

					switch (this.logLevel)
					{
						case 0:
							logConf.Targets.Trace.Verbose = VerboseLevel.Alarm;
							break;
						case 1:
							logConf.Targets.Trace.Verbose = VerboseLevel.Standard;
							break;
						case 2:
							logConf.Targets.Trace.Verbose = VerboseLevel.Interaction;
							break;
						case 3:
							logConf.Targets.Trace.Verbose = VerboseLevel.Trace;
							break;
						case 4:
							logConf.Targets.Trace.Verbose = VerboseLevel.Debug;
							break;
					}

					FileConfiguration fileConf = new FileConfiguration(true, logConf.Targets.Trace.Verbose, "logs" + Path.DirectorySeparatorChar + this.logFile);
					fileConf.MessageHeaderFormat = MessageHeaderFormat.Medium;

					logConf.Targets.Files.Add(fileConf);

					this.endpointLogger = LoggerFactory.CreateRootLogger("SipEndpoint", logConf);
					this.Logger = this.endpointLogger.CreateChildLogger("QuickStart");

					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint(this.endpointLogger);
				}
				else
				{
					// Setup NULL logger
					this.nullLogger = new NullLogger();
					this.Logger = this.nullLogger;
					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint();
				}

				// OMITTED: Endpoint configuration

				this.provider = this.endpoint.Resolve("IEndpointPovider") as SipProvider;

				// Setup Endpoint Logger
				if (this.enableLogging)
					this.provider.SetEndpointLogger(this.endpointLogger);
				else
					this.provider.SetEndpointLogger(this.nullLogger);

				this.endpoint.ApplyConfiguration(confDoc.Root);

				// OMITTED:
				//this.endpoint.BeginActivate();

				// At this point the actual configuration can be updated and
				// Then the Endpoint can be started
				// The next two lines of the code are unnecessary if configuration
				// is not going to be changed

				// Get updated configuration settings
				//confDoc = XDocument.Load("SipEndpoint.config");
				//this.endpoint.ApplyConfiguration(confDoc.Root);

				// The actual SIP Endpoint Start
				// OMITTED:
				//this.endpoint.Start();
				//this.Logger.Debug("this.endpoint.Start()");
			
			// OMITTED: No empty try-catch
			//}
			//catch (Exception exception)
			//{
			//	//this.Logger.Debug("2 RunUpEndpoint()" + exception.Message);
			//	//System.Windows.Forms.MessageBox.Show(exception.Message);
			//}
		}
 public void LogSink_LogSinkHasInternalLogger()
 {
     LogConfiguration configuration = new LogConfiguration();
     StringSink sink = new StringSink { Name = "fake" };
     configuration.Sinks.Add(sink);
     LogKernel kernel = new LogKernel(configuration);
     Assert.IsNotNull(sink.InternalLogger);
 }
Example #53
0
        public static void Main(string[] args)
        {
            LogConfiguration loggerConfiguration = new LogConfiguration
            {
                Transmission = new TransmissionConfiguration { EnableAutomatedTelemetry = true },
                Identifiers = new Dictionary<string, string> { { "MachineName", Environment.MachineName } }
            };

            string tenantToken = ConfigurationManager.AppSettings["AriaTenantToken"];
            ILogger logger = Microsoft.Applications.Telemetry.Server.LogManager.Initialize(tenantToken, loggerConfiguration);

            logger.LogEvent(new EventProperties("Starting"));

            if (args.Contains("-break"))
            {
                Logger.Info("Breaking into debugger");
                Debugger.Break();
            }

            try
            {
                string configPath = ConfigurationManager.AppSettings["ConfigPath"];
                string[] configsFilePattern = ConfigurationManager.AppSettings["ConfigFilePattern"].Split(',');
                List<string> configFiles = new List<string>();
                foreach (string configpat in configsFilePattern)
                {
                    var configFileNames = Directory.GetFiles(configPath, configpat);
                    configFiles.AddRange(configFileNames);
                }

                logger.LogSampledMetric("ConfigFilesFound", configFiles.Count);
                if (configFiles.Count == 0)
                {
                    Logger.ErrorFormat("No configs found (path='{0}', pattern='{1}')", configPath, configsFilePattern);
                    throw new ConfigurationErrorsException("No configs found");
                }

                var configs = new List<Config>();
                var configTimeStamps = new Dictionary<string, DateTime>();

                foreach (var configFile in configFiles)
                {
                    // Save the timestamp for the config so that we can detect if it changed later on
                    configTimeStamps[configFile] = File.GetLastWriteTime(configFile);

                    // Load the config and add it to the list.
                    // If loading failed, print error message and continue
                    var cfg = TryLoadConfig(configFile);
                    if (cfg == null)
                    {
                        Logger.ErrorFormat("Couldn't load config file {0}. Skipping that config file.", configFile);
                        continue;
                    }

                    configs.Add(cfg);
                }

                logger.LogSampledMetric("ConfigFilesLoaded", configs.Count);
                if (configs.Count == 0)
                {
                    throw new ConfigurationErrorsException("None of the configs were valid.");
                }

                InitInstances(configs);

                var iterations = ReadIntFromAppConfig("Iterations", 200);
                var interval = TimeSpan.FromSeconds(ReadIntFromAppConfig("IntervalInSeconds", 1));
                var useThreads = ReadBoolFromAppConfig("UseThreads", false);

                for (var i = 0; i < iterations; ++i)
                {
                    Logger.InfoFormat("{0} Iteration {1} {0}", new string('-', 15), i);
                    RunInstances(useThreads);

                    if (IsConfigsChanged(configTimeStamps))
                    {
                        break;
                    }

                    Thread.CurrentThread.Join(interval); // Sleep between iterations
                }

                foreach (var instance in _instances)
                {
                    var disposable = instance as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
             catch (Exception exception)
            {
                Logger.ErrorFormat("Exception caught in main - aborting. {0}", exception);
            }
        }
        public void LogSink_LogSinkCanWriteToInternalLogger()
        {
            LogConfiguration configuration = new LogConfiguration();
            configuration.InternalLogger.Enabled = true;
            configuration.Sinks.Add(new TestSink());
            LogKernel kernel = new LogKernel(configuration);
            ILogger logger = kernel.GetLogger();

            using (StringTraceListenerScope scope = new StringTraceListenerScope())
            {
                Assert.AreEqual(0, scope.Listener.Messages.Count);
                logger.Write(LogLevel.Information, "TestMessage");
                Assert.AreEqual(1, scope.Listener.Messages.Count);
                Assert.AreEqual("TestMessage", scope.Listener.Messages[0]);
            }
        }
        private static bool ParseConfiguration(string configurationXml, Dictionary<string, LogConfiguration> loggers)
        {
            bool clean = true; // used to track whether any errors were encountered

            if (string.IsNullOrEmpty(configurationXml))
            {
                return true; // it's okay to have nothing at all
            }

            var configuration = new XmlDocument();
            try
            {
                configuration.LoadXml(configurationXml);
            }
            catch (XmlException)
            {
                InternalLogger.Write.InvalidConfiguration("Configuration was not valid XML");
                return false;
            }

            XmlNode node = configuration.SelectSingleNode(EtwOverrideXpath);
            if (node != null)
            {
                XmlNode setting = node.Attributes.GetNamedItem(EtwOverrideEnabledAttribute);
                bool isEnabled = (AllowEtwLogging == AllowEtwLoggingValues.Enabled);
                if (setting == null || !bool.TryParse(setting.Value, out isEnabled))
                {
                    InternalLogger.Write.InvalidConfiguration(EtwOverrideXpath + " tag has invalid " +
                                                              EtwOverrideEnabledAttribute + " attribute");
                    clean = false;
                }

                AllowEtwLogging = isEnabled ? AllowEtwLoggingValues.Enabled : AllowEtwLoggingValues.Disabled;
            }

            foreach (XmlNode log in configuration.SelectNodes(LogTagXpath))
            {
                string name = GetLogNameFromNode(log);
                LoggerType type = GetLogTypeFromNode(log);

                if (type == LoggerType.None)
                {
                    // GetLogTypeFromNode logs this particular error.
                    clean = false;
                    continue;
                }

                if (type == LoggerType.Console)
                {
                    if (name != null)
                    {
                        InternalLogger.Write.InvalidConfiguration("console log should not have a name");
                        clean = false;
                    }

                    // We use a special name for the console logger that is invalid for file loggers so we can track
                    // it along with them.
                    name = ConsoleLoggerName;
                }
                else
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        InternalLogger.Write.InvalidConfiguration("cannot configure a log with no name");
                        clean = false;
                        continue;
                    }
                    if (name.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
                    {
                        InternalLogger.Write.InvalidConfiguration("base name of log is invalid " + name);
                        clean = false;
                        continue;
                    }

                    if (type == LoggerType.ETLFile && AllowEtwLogging == AllowEtwLoggingValues.Disabled)
                    {
                        InternalLogger.Write.OverridingEtwLogging(name);
                        type = LoggerType.TextLogFile;
                    }
                }

                // We wish to update existing configuration where possible.
                LogConfiguration config;
                if (!loggers.TryGetValue(name, out config))
                {
                    config = new LogConfiguration();
                }

                config.FileType = type;
                clean &= ParseLogNode(log, config);

                if (config.NamedSources.Count + config.GuidSources.Count == 0)
                {
                    InternalLogger.Write.InvalidConfiguration("log destination " + name + " has no valid sources");
                    clean = false;
                    continue;
                }

                // Ensure what we got has been sanitized. We currently don't do stringent checks on the console logger
                // to see if useless stuff like a rotation interval or buffer size is set, but could in the future get
                // more picky.
                if (config.Filters.Count > 0 && !config.HasFeature(LogConfiguration.Features.RegexFilter))
                {
                    InternalLogger.Write.InvalidConfiguration("log destination " + name + " has filters but type " +
                                                              type + " does not support this feature.");
                    clean = false;
                    config.Filters.Clear();
                }

                loggers[name] = config;
            }

            return clean;
        }
 public void LogConfiguration_Clone()
 {
     LogConfiguration configuration = new LogConfiguration();
     LogConfiguration clonedConfiguration = new LogConfiguration();
     Assert.AreNotSame(configuration, clonedConfiguration);
 }