Exemplo n.º 1
0
        private static void ConfigureLog4Net()
        {
            var layout = new PatternLayout
            {
                ConversionPattern = "%d [%property{BusinessCorrelationId}] %-5p %c - %m%n"
            };

            layout.ActivateOptions();

            var consoleAppender = new ConsoleAppender
            {
                Threshold = Level.Info,
                Layout    = layout
            };

            consoleAppender.ActivateOptions();

            var executingAssembly = Assembly.GetExecutingAssembly();
            var repository        = log4net.LogManager.GetRepository(executingAssembly);

            BasicConfigurator.Configure(repository, consoleAppender);

            // Tell NServiceBus to use Log4Net
            LogManager.Use <Log4NetFactory>();
        }
        public async Task Should_log_nsb_logs()
        {
            var config       = new NLog.Config.LoggingConfiguration();
            var memoryTarget = new NLog.Targets.MemoryTarget();

            config.AddRuleForAllLevels(memoryTarget);
            LogManager.Configuration = config;

            NsbLogManager.UseFactory(new ExtensionsLoggerFactory(new NLogLoggerFactory()));

            var endpointConfiguration = new EndpointConfiguration("LoggingTests");

            endpointConfiguration.EnableInstallers();
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.UseTransport(new LearningTransport());
            endpointConfiguration.UsePersistence <LearningPersistence>();

            var endpoint = await Endpoint.Start(endpointConfiguration)
                           .ConfigureAwait(false);

            try
            {
                Assert.IsNotEmpty(memoryTarget.Logs);
            }
            finally
            {
                await endpoint.Stop()
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 3
0
        public IBus Start(bool isRunningAcceptanceTests = false)
        {
            var logger = LogManager.GetLogger(typeof(Bootstrapper));

            if (!isRunningAcceptanceTests)
            {
                var startOptions = new StartOptions(settings.RootUrl);

                WebApp = Microsoft.Owin.Hosting.WebApp.Start(startOptions, b => Startup.Configuration(b));
            }

            bus = NServiceBusFactory.CreateAndStart(settings, container, host, documentStore, configuration);

            logger.InfoFormat("Api is now accepting requests on {0}", settings.ApiUrl);

            return(bus);
        }
Exemplo n.º 4
0
        private void RecordStartup(LoggingSettings loggingSettings)
        {
            var version        = typeof(Bootstrapper).Assembly.GetName().Version;
            var startupMessage = $@"
-------------------------------------------------------------
ServiceControl Version:       {version}
Selected Transport:           {settings.TransportType}
Audit Retention Period:       {settings.AuditRetentionPeriod}
Error Retention Period:       {settings.ErrorRetentionPeriod}
Forwarding Error Messages:    {settings.ForwardErrorMessages}
Forwarding Audit Messages:    {settings.ForwardAuditMessages}
Database Size:                {DataSize()}bytes
ServiceControl Logging Level: {loggingSettings.LoggingLevel}
RavenDB Logging Level:        {loggingSettings.RavenDBLogLevel}
-------------------------------------------------------------";

            var logger = LogManager.GetLogger(typeof(Bootstrapper));

            logger.Info(startupMessage);
        }
Exemplo n.º 5
0
        private void ConfigureLogging(LoggingSettings loggingSettings)
        {
            LogManager.Use <NLogFactory>();

            const long megaByte = 1073741824;

            if (NLog.LogManager.Configuration != null)
            {
                return;
            }

            var version      = typeof(Bootstrapper).Assembly.GetName().Version;
            var nlogConfig   = new LoggingConfiguration();
            var simpleLayout = new SimpleLayout("${longdate}|${threadid}|${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}");
            var header       = $@"-------------------------------------------------------------
ServiceControl Version:				{version}
Selected Transport:					{settings.TransportType}
Audit Retention Period:				{settings.AuditRetentionPeriod}
Error Retention Period:				{settings.ErrorRetentionPeriod}
Forwarding Error Messages:		{settings.ForwardErrorMessages}
Forwarding Audit Messages:		{settings.ForwardAuditMessages}
Database Size:							{DataSize()}bytes
-------------------------------------------------------------";

            var fileTarget = new FileTarget
            {
                ArchiveEvery     = FileArchivePeriod.Day,
                FileName         = Path.Combine(loggingSettings.LogPath, "logfile.${shortdate}.txt"),
                ArchiveFileName  = Path.Combine(loggingSettings.LogPath, "logfile.{#}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                Layout           = simpleLayout,
                MaxArchiveFiles  = 14,
                ArchiveAboveSize = 30 * megaByte,
                Header           = new SimpleLayout(header)
            };


            var ravenFileTarget = new FileTarget
            {
                ArchiveEvery     = FileArchivePeriod.Day,
                FileName         = Path.Combine(loggingSettings.LogPath, "ravenlog.${shortdate}.txt"),
                ArchiveFileName  = Path.Combine(loggingSettings.LogPath, "ravenlog.{#}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                Layout           = simpleLayout,
                MaxArchiveFiles  = 14,
                ArchiveAboveSize = 30 * megaByte,
                Header           = new SimpleLayout(header)
            };

            var consoleTarget = new ColoredConsoleTarget
            {
                Layout = simpleLayout,
                UseDefaultRowHighlightingRules = true
            };

            var nullTarget = new NullTarget();

            // There lines don't appear to be necessary.  The rules seem to work without implicitly adding the targets?!?
            nlogConfig.AddTarget("console", consoleTarget);
            nlogConfig.AddTarget("debugger", fileTarget);
            nlogConfig.AddTarget("raven", ravenFileTarget);
            nlogConfig.AddTarget("bitbucket", nullTarget);

            // Only want to see raven errors
            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", loggingSettings.RavenDBLogLevel, ravenFileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Error, consoleTarget)); //Noise reduction - Only RavenDB errors on the console
            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Debug, nullTarget)
            {
                Final = true
            }); //Will swallow debug and above messages


            // Always want to see license logging regardless of default logging level
            nlogConfig.LoggingRules.Add(new LoggingRule("Particular.ServiceControl.Licensing.*", LogLevel.Info, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("Particular.ServiceControl.Licensing.*", LogLevel.Info, consoleTarget)
            {
                Final = true
            });

            // Defaults
            nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LoggingLevel, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LoggingLevel < LogLevel.Info ? loggingSettings.LoggingLevel : LogLevel.Info, consoleTarget));

            // Remove Console Logging when running as a service
            if (!Environment.UserInteractive)
            {
                foreach (var rule in nlogConfig.LoggingRules.Where(p => p.Targets.Contains(consoleTarget)).ToList())
                {
                    nlogConfig.LoggingRules.Remove(rule);
                }
            }

            NLog.LogManager.Configuration = nlogConfig;

            var logger       = LogManager.GetLogger(typeof(Bootstrapper));
            var logEventInfo = new LogEventInfo
            {
                TimeStamp = DateTime.Now
            };

            logger.InfoFormat("Logging to {0} with LoggingLevel '{1}'", fileTarget.FileName.Render(logEventInfo), loggingSettings.LoggingLevel.Name);
            logger.InfoFormat("RavenDB logging to {0} with LoggingLevel '{1}'", ravenFileTarget.FileName.Render(logEventInfo), loggingSettings.RavenDBLogLevel.Name);
        }
Exemplo n.º 6
0
        public static void Configure(Settings settings)
        {
            LogManager.Use <NLogFactory>();

            if (NLog.LogManager.Configuration != null)
            {
                return;
            }

            var version      = typeof(Host).Assembly.GetName().Version;
            var nlogConfig   = new LoggingConfiguration();
            var simpleLayout = new SimpleLayout("${longdate}|${threadid}|${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}");
            var header       = $@"-------------------------------------------------------------
ServiceControl Monitoring Version:				{version}
Selected Transport:					{settings.TransportType}
-------------------------------------------------------------";

            var fileTarget = new FileTarget
            {
                ArchiveEvery     = FileArchivePeriod.Day,
                FileName         = Path.Combine(settings.LogPath, "logfile.${shortdate}.txt"),
                ArchiveFileName  = Path.Combine(settings.LogPath, "logfile.{#}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                Layout           = simpleLayout,
                MaxArchiveFiles  = 14,
                ArchiveAboveSize = 30 * MegaByte,
                Header           = new SimpleLayout(header)
            };

            var consoleTarget = new ColoredConsoleTarget
            {
                Layout = simpleLayout,
                UseDefaultRowHighlightingRules = true
            };

            var nullTarget = new NullTarget();

            nlogConfig.AddTarget("console", consoleTarget);
            nlogConfig.AddTarget("debugger", fileTarget);
            nlogConfig.AddTarget("null", nullTarget);

            //Suppress NSB license logging since this will have it's own
            nlogConfig.LoggingRules.Add(new LoggingRule("NServiceBus.LicenseManager", LogLevel.Info, nullTarget)
            {
                Final = true
            });

            // Always want to see license logging regardless of default logging level
            nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.Monitoring.Licensing.*", LogLevel.Info, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.Monitoring.Licensing.*", LogLevel.Info, consoleTarget)
            {
                Final = true
            });

            // Defaults
            nlogConfig.LoggingRules.Add(new LoggingRule("*", settings.LogLevel, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("*", settings.LogLevel < LogLevel.Info ? settings.LogLevel : LogLevel.Info, consoleTarget));

            // Remove Console Logging when running as a service
            if (!Environment.UserInteractive)
            {
                foreach (var rule in nlogConfig.LoggingRules.Where(p => p.Targets.Contains(consoleTarget)).ToList())
                {
                    nlogConfig.LoggingRules.Remove(rule);
                }
            }

            NLog.LogManager.Configuration = nlogConfig;

            var logger       = LogManager.GetLogger("LoggingConfiguration");
            var logEventInfo = new LogEventInfo
            {
                TimeStamp = DateTime.Now
            };

            logger.InfoFormat("Logging to {0} with LogLevel '{1}'", fileTarget.FileName.Render(logEventInfo), settings.LogLevel.Name);
        }
Exemplo n.º 7
0
        private void InitializeServiceControl(ScenarioContext context)
        {
            LogManager.Use <NLogFactory>();
            NLog.LogManager.Configuration = SetupLogging(Settings.DEFAULT_SERVICE_NAME);

            var settings = new Settings
            {
                Port   = port,
                DbPath = ravenPath,
                ForwardErrorMessages         = false,
                ForwardAuditMessages         = false,
                TransportType                = transportToUse.TypeName,
                TransportConnectionString    = transportToUse.ConnectionString,
                ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(2),
                MaximumConcurrencyLevel      = 2,
                HttpDefaultConnectionLimit   = int.MaxValue
            };

            SetSettings(settings);

            var configuration = new BusConfiguration();

            configuration.TypesToScan(GetTypesScopedByTestClass(transportToUse).Concat(new[]
            {
                typeof(MessageMapperInterceptor),
                typeof(RegisterWrappers),
                typeof(SessionCopInBehavior),
                typeof(SessionCopInBehaviorForMainPipe),
                typeof(TraceIncomingBehavior),
                typeof(TraceOutgoingBehavior)
            }));
            configuration.EnableInstallers();

            configuration.GetSettings().SetDefault("ScaleOut.UseSingleBrokerQueue", true);
            configuration.GetSettings().Set("SC.ScenarioContext", context);

            // This is a hack to ensure ServiceControl picks the correct type for the messages that come from plugins otherwise we pick the type from the plugins assembly and that is not the type we want, we need to pick the type from ServiceControl assembly.
            // This is needed because we no longer use the AppDomain separation.
            configuration.EnableFeature <MessageMapperInterceptor>();
            configuration.RegisterComponents(r => { configuration.GetSettings().Set("SC.ConfigureComponent", r); });

            configuration.RegisterComponents(r =>
            {
                r.RegisterSingleton(context.GetType(), context);
                r.RegisterSingleton(typeof(ScenarioContext), context);
            });

            configuration.Pipeline.Register <SessionCopInBehavior.Registration>();
            configuration.Pipeline.Register <SessionCopInBehaviorForMainPipe.Registration>();
            configuration.Pipeline.Register <TraceIncomingBehavior.Registration>();
            configuration.Pipeline.Register <TraceOutgoingBehavior.Registration>();

            CustomConfiguration(configuration);

            using (new DiagnosticTimer("Initializing Bootstrapper"))
            {
                bootstrapper = new Bootstrapper(settings, configuration);
            }
            using (new DiagnosticTimer("Initializing AppBuilder"))
            {
                var app = new AppBuilder();
                bootstrapper.Startup.Configuration(app);
                var appFunc = app.Build();

                Handler = new OwinHttpMessageHandler(appFunc)
                {
                    UseCookies        = false,
                    AllowAutoRedirect = false
                };
                httpClient = new HttpClient(Handler);
            }

            using (new DiagnosticTimer("Creating and starting Bus"))
            {
                bus = bootstrapper.Start(true);
            }
        }
Exemplo n.º 8
0
        private void InitializeServiceControl(ScenarioContext context, string[] instanceNames)
        {
            if (instanceNames.Length == 0)
            {
                instanceNames = new[] { Settings.DEFAULT_SERVICE_NAME };
            }

            // how to deal with the statics here?
            LogManager.Use <NLogFactory>();
            NLog.LogManager.Configuration = SetupLogging(Settings.DEFAULT_SERVICE_NAME);

            var startPort = 33333;

            foreach (var instanceName in instanceNames)
            {
                startPort = FindAvailablePort(startPort);
                var settings = new Settings(instanceName)
                {
                    Port   = startPort++,
                    DbPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()),
                    ForwardErrorMessages         = false,
                    ForwardAuditMessages         = false,
                    TransportType                = transportToUse.TypeName,
                    TransportConnectionString    = transportToUse.ConnectionString,
                    ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(2),
                    MaximumConcurrencyLevel      = 2,
                    HttpDefaultConnectionLimit   = int.MaxValue
                };

                if (instanceName == Settings.DEFAULT_SERVICE_NAME)
                {
                    SetSettings(settings);
                }

                SetInstanceSettings(instanceName, settings);
                SettingsPerInstance[instanceName] = settings;

                var configuration = new BusConfiguration();
                configuration.TypesToScan(GetTypesScopedByTestClass(transportToUse).Concat(new[]
                {
                    typeof(MessageMapperInterceptor),
                    typeof(RegisterWrappers),
                    typeof(SessionCopInBehavior),
                    typeof(SessionCopInBehaviorForMainPipe),
                    typeof(TraceIncomingBehavior),
                    typeof(TraceOutgoingBehavior)
                }));
                configuration.EnableInstallers();

                configuration.GetSettings().SetDefault("ScaleOut.UseSingleBrokerQueue", true);
                configuration.GetSettings().Set("SC.ScenarioContext", context);

                // This is a hack to ensure ServiceControl picks the correct type for the messages that come from plugins otherwise we pick the type from the plugins assembly and that is not the type we want, we need to pick the type from ServiceControl assembly.
                // This is needed because we no longer use the AppDomain separation.
                configuration.EnableFeature <MessageMapperInterceptor>();
                configuration.RegisterComponents(r => { configuration.GetSettings().Set("SC.ConfigureComponent", r); });

                configuration.RegisterComponents(r =>
                {
                    r.RegisterSingleton(context.GetType(), context);
                    r.RegisterSingleton(typeof(ScenarioContext), context);
                });

                configuration.Pipeline.Register <SessionCopInBehavior.Registration>();
                configuration.Pipeline.Register <SessionCopInBehaviorForMainPipe.Registration>();
                configuration.Pipeline.Register <TraceIncomingBehavior.Registration>();
                configuration.Pipeline.Register <TraceOutgoingBehavior.Registration>();

                if (instanceName == Settings.DEFAULT_SERVICE_NAME)
                {
                    CustomConfiguration(configuration);
                }

                CustomInstanceConfiguration(instanceName, configuration);

                Bootstrapper bootstrapper;
                using (new DiagnosticTimer($"Initializing Bootstrapper for {instanceName}"))
                {
                    var loggingSettings = new LoggingSettings(settings.ServiceName);
                    bootstrapper = new Bootstrapper(() => { }, settings, configuration, loggingSettings);
                    bootstrappers[instanceName]    = bootstrapper;
                    bootstrapper.HttpClientFactory = HttpClientFactory;
                }
                using (new DiagnosticTimer($"Initializing AppBuilder for {instanceName}"))
                {
                    var app = new AppBuilder();
                    bootstrapper.Startup.Configuration(app);
                    var appFunc = app.Build();

                    var handler = new OwinHttpMessageHandler(appFunc)
                    {
                        UseCookies        = false,
                        AllowAutoRedirect = false
                    };
                    Handlers[instanceName]       = handler;
                    portToHandler[settings.Port] = handler; // port should be unique enough
                    var httpClient = new HttpClient(handler);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClients[instanceName] = httpClient;
                }

                using (new DiagnosticTimer($"Creating and starting Bus for {instanceName}"))
                {
                    busses[instanceName] = bootstrapper.Start(true);
                }
            }

            // how to deal with the statics here?
            ArchivingManager.ArchiveOperations = new Dictionary <string, InMemoryArchive>();
            RetryingManager.RetryOperations    = new Dictionary <string, InMemoryRetry>();
        }