public void TestGetSafeScrubFields()
        {
            var scrubFields             = new string[] { "one", "two", "three", };
            var scrubSafelistFields     = new string[] { "two", };
            var expectedSafeScrubFields = new string[] { "one", "three", };

            var destinationOptions  = new RollbarDestinationOptions(RollbarUnitTestSettings.AccessToken, RollbarUnitTestSettings.Environment);
            var dataSecurityOptions = new RollbarDataSecurityOptions();

            dataSecurityOptions.ScrubFields         = scrubFields;
            dataSecurityOptions.ScrubSafelistFields = scrubSafelistFields;

            var loggerConfig = new RollbarLoggerConfig(RollbarUnitTestSettings.AccessToken);

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
            loggerConfig.RollbarDataSecurityOptions.Reconfigure(dataSecurityOptions);

            var result = loggerConfig.RollbarDataSecurityOptions.GetFieldsToScrub();

            Assert.AreEqual(expectedSafeScrubFields.Length, result.Count);
            foreach (var expected in expectedSafeScrubFields)
            {
                Assert.IsTrue(result.Contains(expected));
            }
        }
        public void FaultyTruncateTest()
        {
            this.Reset();

            RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
            RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();

            payloadManipulationOptions.Truncate = delegate(Payload payload)
            {
                throw new Exception("Buggy truncate delegate!");
            };
            config.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);

            using (IRollbar rollbar = this.ProvideDisposableRollbar())
            {
                rollbar.Configure(config);

                rollbar.Critical("This message's Truncate will fail!");

                this.VerifyInstanceOperational(rollbar);
                // one more extra sanity check:
                Assert.AreEqual(0, RollbarQueueController.Instance.GetTotalPayloadCount());
            }

            this.Reset();
        }
        public void ThrowsExceptionWhenConfiguredWithInvalidConfigInstance()
        {
            RollbarLoggerConfig invalidConfig = new RollbarLoggerConfig(string.Empty);

            invalidConfig.RollbarPayloadAdditionOptions.Person = new Person();

            var rollbar = RollbarFactory.CreateNew();

            try
            {
                rollbar.Configure(invalidConfig);
            }
            catch (RollbarException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.ToString());
                Assert.IsTrue(ex.Data.Count > 0, "Expected to contain failed validation rules!");
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.ToString());
                Assert.Fail("Should never reach here due to exception above!");
            }

            Assert.Fail("Should never reach here due to exception above!");
        }
        public void TestReconfiguration()
        {
            RollbarLoggerConfig config = new RollbarLoggerConfig();

            Assert.AreEqual("seedToken", config.RollbarDestinationOptions.AccessToken);
            Console.WriteLine(config.TraceAsString());
            config.Reconfigured += Config_Reconfigured;
            Assert.AreEqual(0, this._actualReconfigCount);
            IRollbarDestinationOptions rollbarDestinationOptions = config.RollbarDestinationOptions;

            RollbarDestinationOptions destinationOptions = new RollbarDestinationOptions();

            destinationOptions.AccessToken = "CUSTOM";
            config.RollbarDestinationOptions.Reconfigure(destinationOptions);
            Assert.AreEqual(1, this._actualReconfigCount);
            Assert.AreSame(rollbarDestinationOptions, config.RollbarDestinationOptions);
            Assert.AreEqual("CUSTOM", config.RollbarDestinationOptions.AccessToken, "Options reconfig works!");
            Console.WriteLine(config.TraceAsString());

            RollbarLoggerConfig newConfig = new RollbarLoggerConfig();

            Assert.AreEqual("seedToken", newConfig.RollbarDestinationOptions.AccessToken);
            Console.WriteLine(newConfig.TraceAsString());
            Assert.AreNotSame(rollbarDestinationOptions, newConfig.RollbarDestinationOptions);
            newConfig.Reconfigured   += Config_Reconfigured;
            rollbarDestinationOptions = newConfig.RollbarDestinationOptions;

            newConfig.Reconfigure(config);
            Assert.AreEqual(8, this._actualReconfigCount);
            Assert.AreEqual("CUSTOM", newConfig.RollbarDestinationOptions.AccessToken, "Structured config's reconfig works!");
            Console.WriteLine(newConfig.TraceAsString());
            Assert.AreSame(rollbarDestinationOptions, newConfig.RollbarDestinationOptions);
            Assert.AreNotSame(config, newConfig);
            Assert.AreNotSame(config.RollbarDestinationOptions, newConfig.RollbarDestinationOptions);
        }
        public void TransmitConfigOptionWorks()
        {
            this.Reset();

            RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;

            using IRollbar rollbar = this.ProvideDisposableRollbar();
            rollbar.Configure(config);
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.Critical("Transmission is expected to happen!");
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to happen!");

            config.RollbarDeveloperOptions.Transmit = false;
            rollbar.Configure(config);
            this.IncrementCount <TransmissionOmittedEventArgs>();
            rollbar.Critical("Transmission is expected to be omitted!");
            this.IncrementCount <TransmissionOmittedEventArgs>();
            rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to be omitted!");

            config.RollbarDeveloperOptions.Transmit = true;
            rollbar.Configure(config);
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.Critical("Transmission is expected to happen!");
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to happen!");
        }
        public void TestDefaultScrubFields()
        {
            var config = new RollbarLoggerConfig(RollbarUnitTestSettings.AccessToken);

            Assert.IsTrue(
                new HashSet <string>(config.RollbarDataSecurityOptions.ScrubFields).IsSupersetOf(RollbarDataScrubbingHelper.Instance.GetDefaultFields())
                );
        }
示例#7
0
        public PayloadFixture()
        {
            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(RollbarUnitTestSettings.AccessToken, RollbarUnitTestSettings.Environment);

            this._config = new RollbarLoggerConfig();
            this._config.RollbarDestinationOptions.Reconfigure(destinationOptions);
        }
        public void ConvenienceMethodsUseAppropriateErrorLevels(ErrorLevel expectedLogLevel)
        {
            var acctualLogLevel = ErrorLevel.Info;

            void Transform(Payload payload)
            {
                acctualLogLevel = payload.Data.Level.Value;
            }

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarPayloadManipulationOptions payloadManipulationOptions =
                new RollbarPayloadManipulationOptions(Transform);
            var loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
            loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
            using (var logger = RollbarFactory.CreateNew().Configure(loggerConfig))
            {
                try
                {
                    var blockingLogger = logger.AsBlockingLogger(TimeSpan.FromMilliseconds(TIME_OUT));
                    var ex             = new Exception();
                    switch (expectedLogLevel)
                    {
                    case ErrorLevel.Critical:
                        blockingLogger.Critical(ex);
                        break;

                    case ErrorLevel.Error:
                        blockingLogger.Error(ex);
                        break;

                    case ErrorLevel.Warning:
                        blockingLogger.Warning(ex);
                        break;

                    case ErrorLevel.Info:
                        blockingLogger.Info(ex);
                        break;

                    case ErrorLevel.Debug:
                        blockingLogger.Debug(ex);
                        break;
                    }
                }
                catch
                {
                    Assert.Fail();
                }
            }

            Assert.AreEqual(expectedLogLevel, acctualLogLevel);
        }
 public void TestInstanceCreation()
 {
     try
     {
         RollbarLoggerConfig rConfig = new RollbarLoggerConfig(RollbarUnitTestSettings.AccessToken);
     }
     catch
     {
         Assert.Fail("The instance creation is expected to succeed, but did not!");
     }
 }
        /// <summary>
        /// Gets the deployments page asynchronously.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="pageNumber">The page number.</param>
        /// <returns></returns>
        public async Task <IDeploymentDetails[]?> GetDeploymentsPageAsync(string environment, int pageNumber)
        {
            Assumption.AssertNotNullOrWhiteSpace(this._readAccessToken, nameof(this._readAccessToken));

            var config = new RollbarLoggerConfig(this._readAccessToken);

            using HttpClient httpClient = new();
            RollbarDeployClient rollbarClient = new(config, httpClient);
            var result = await rollbarClient.GetDeploymentsAsync(this._readAccessToken, pageNumber).ConfigureAwait(false);

            return(result?.DeploysPage?.Deploys);
        }
        /// <summary>
        /// Gets the deployment asynchronously.
        /// </summary>
        /// <param name="deploymentID">The deployment identifier.</param>
        /// <returns></returns>
        public async Task <IDeploymentDetails?> GetDeploymentAsync(string deploymentID)
        {
            Assumption.AssertNotNullOrWhiteSpace(deploymentID, nameof(deploymentID));
            Assumption.AssertNotNullOrWhiteSpace(this._readAccessToken, nameof(this._readAccessToken));

            var config = new RollbarLoggerConfig(this._readAccessToken);

            using HttpClient httpClient = new();
            RollbarDeployClient rollbarClient = new(config, httpClient);
            var result = await rollbarClient.GetDeploymentAsync(this._readAccessToken, deploymentID);

            return(result?.Deploy);
        }
        /// <summary>
        /// Registers the deployment asynchronously.
        /// </summary>
        /// <param name="deployment">The deployment.</param>
        /// <returns></returns>
        public async Task RegisterAsync(IDeployment deployment)
        {
            Assumption.AssertNotNullOrWhiteSpace(this._writeAccessToken, nameof(this._writeAccessToken));

            RollbarDestinationOptions destinationOptions = new(this._writeAccessToken, deployment.Environment);
            var config = new RollbarLoggerConfig();

            config.RollbarDestinationOptions.Reconfigure(destinationOptions);

            using HttpClient httpClient = new();
            RollbarDeployClient rollbarClient = new(config, httpClient);
            await rollbarClient.PostAsync(deployment);
        }
示例#13
0
        public void SetupFixture()
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );

            this._loggerConfig =
                new RollbarLoggerConfig();
            this._loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
        }
        public void RethrowConfigOptionWorks()
        {
            this.Reset();

            RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;

            using IRollbar rollbar = this.ProvideDisposableRollbar();
            rollbar.Configure(config);
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged async!"));
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
            .Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged sync!"));

            int rethrowCount = 0;

            config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting = true;
            rollbar.Configure(config);
            try
            {
                this.IncrementCount <CommunicationEventArgs>();
                rollbar.Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged async with rethrow!"));
            }
            catch
            {
                rethrowCount++;
            }

            try
            {
                this.IncrementCount <CommunicationEventArgs>();
                rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
                .Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged sync with rethrow!"));
            }
            catch
            {
                rethrowCount++;
            }

            config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting = false;
            rollbar.Configure(config);
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged async!"));
            this.IncrementCount <CommunicationEventArgs>();
            rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
            .Critical(ExceptionSimulator.GetExceptionWith(5, "Exception logged sync!"));

            Assert.AreEqual(2, rethrowCount, "matching total of rethrows...");
        }
        public void TestBasics()
        {
            RollbarLoggerConfig config = new RollbarLoggerConfig();

            Console.WriteLine(config.TraceAsString());

            var results = config.Validate();

            Assert.AreEqual(1, results.Count, "One Validation Rule failed!");
            Console.WriteLine("Validation Results:");
            foreach (var result in results)
            {
                Console.WriteLine($"  {result}");
            }
            Console.WriteLine();
        }
        /// <summary>
        /// Provides the live rollbar configuration.
        /// </summary>
        /// <param name="rollbarAccessToken">The rollbar access token.</param>
        /// <param name="rollbarEnvironment">The rollbar environment.</param>
        /// <returns>IRollbarConfig.</returns>
        protected IRollbarLoggerConfig ProvideLiveRollbarConfig(string rollbarAccessToken, string rollbarEnvironment)
        {
            if (this._loggerConfig == null)
            {
                RollbarDestinationOptions destinationOptions =
                    new RollbarDestinationOptions(rollbarAccessToken, rollbarEnvironment);

                RollbarDataSecurityOptions dataSecurityOptions = new RollbarDataSecurityOptions();
                dataSecurityOptions.ScrubFields = new string[] { "secret", "super_secret", };

                RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
                loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
                loggerConfig.RollbarDataSecurityOptions.Reconfigure(dataSecurityOptions);

                this._loggerConfig = loggerConfig;
            }
            return(this._loggerConfig);
        }
        private static void RequestUserIPPolicyTest(
            IpAddressCollectionPolicy policy
            , string initialUserHost
            , string expectedUserHost
            )
        {
            IRollbarPackage package = new MessagePackage("Some message");

            var rollbarConfig = new RollbarLoggerConfig(RollbarUnitTestSettings.AccessToken);

            rollbarConfig.RollbarDataSecurityOptions.IpAddressCollectionPolicy = policy;
            var msg = FakeHttpRequestMessage(initialUserHost);

            package = new HttpRequestMessagePackageDecorator(package, msg, rollbarConfig);

            var request = package.PackageAsRollbarData().Request;

            Assert.AreEqual(expectedUserHost, request.UserIp);
        }
        public void ReconfigureRollbarTest()
        {
            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig1 =
                new RollbarLoggerConfig();

            loggerConfig1.RollbarDestinationOptions.Reconfigure(destinationOptions);

            destinationOptions.AccessToken =
                RollbarUnitTestSettings.AccessToken.Replace('0', '1');
            RollbarLoggerConfig loggerConfig2 =
                new RollbarLoggerConfig();

            loggerConfig2.RollbarDestinationOptions.Reconfigure(destinationOptions);

            Assert.AreNotEqual(loggerConfig1.RollbarDestinationOptions.AccessToken, loggerConfig2.RollbarDestinationOptions.AccessToken);

            int initialCount  = RollbarQueueController.Instance.GetQueuesCount();
            int initialCount1 = RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken);
            int initialCount2 = RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken);

            Assert.AreEqual(initialCount + 0, RollbarQueueController.Instance.GetQueuesCount());
            Assert.AreEqual(initialCount1 + 0, RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
            Assert.AreEqual(initialCount2 + 0, RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));

            using (var logger1 = RollbarFactory.CreateNew().Configure(loggerConfig1))
            {
                Assert.AreEqual(initialCount + 1, RollbarQueueController.Instance.GetQueuesCount());
                Assert.AreEqual(initialCount1 + 1, RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                Assert.AreEqual(initialCount2 + 0, RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));

                logger1.Configure(loggerConfig2);

                Assert.AreEqual(initialCount + 1, RollbarQueueController.Instance.GetQueuesCount());
                Assert.AreEqual(initialCount1 + 0, RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                Assert.AreEqual(initialCount2 + 1, RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));
            }
        }
        public void ExceptionWhileTransformingPayloadAsync()
        {
            this._transformException = false;

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();

            payloadManipulationOptions.Transform = delegate {
                throw new NullReferenceException();
            };
            loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);

            using IRollbar logger = RollbarFactory.CreateNew().Configure(loggerConfig);
            logger.InternalEvent += Logger_InternalEvent;

            try
            {
                this.IncrementCount <CommunicationEventArgs>();
                logger.Log(ErrorLevel.Error, "test message");
            }
            catch
            {
                logger.InternalEvent -= Logger_InternalEvent;
                Assert.Fail("should never get here!");
                throw;
            }

            this._signal.Wait();
            logger.InternalEvent -= Logger_InternalEvent;

            Assert.IsTrue(this._transformException);
        }
        public void TestBasicValidation(string token, string personId, int expectedTotalFailedRules)
        {
            Person person = null;

            if (personId != null)
            {
                person = new Person()
                {
                    Id = personId
                };
            }

            RollbarLoggerConfig           config          = new RollbarLoggerConfig(token);
            RollbarPayloadAdditionOptions additionOptions = new RollbarPayloadAdditionOptions();

            additionOptions.Person = person;
            config.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);

            var failedValidationRules = config.Validate();

            Assert.AreEqual(expectedTotalFailedRules, failedValidationRules.Count);
        }
        public void MultithreadedStressTest_BlockingLogs()
        {
            RollbarLoggerFixture.stressLogsCount = 0;

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            RollbarInfrastructureOptions infrastructureOptions = new RollbarInfrastructureOptions();

            infrastructureOptions.ReportingQueueDepth = 200;
            RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.Reconfigure(infrastructureOptions);

            this.IncrementCount <CommunicationEventArgs>(RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.ReportingQueueDepth);

            TimeSpan rollbarBlockingTimeout = TimeSpan.FromMilliseconds(55000);

            List <IRollbar> rollbars =
                new List <IRollbar>(MultithreadedStressTestParams.TotalThreads);
            List <ILogger> loggers = new List <ILogger>(MultithreadedStressTestParams.TotalThreads);

            for (int i = 0; i < MultithreadedStressTestParams.TotalThreads; i++)
            {
                var rollbar = RollbarFactory.CreateNew().Configure(loggerConfig);
                loggers.Add(rollbar.AsBlockingLogger(rollbarBlockingTimeout));
                rollbars.Add(rollbar);
            }

            PerformTheMultithreadedStressTest(loggers.ToArray());

            rollbars.ForEach(r => {
                r.Dispose();
            });
        }
        public static async Task Main(string[] args)
        {
            RollbarLoggerConfig rollbarConfig = new RollbarLoggerConfig(
                RollbarSamplesSettings.AccessToken,
                RollbarSamplesSettings.Environment
                );

            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("#app");

            builder.Services.AddScoped(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            builder.Services.AddLogging(configure =>
                                        configure
                                        .AddFilter(levelFilter => levelFilter >= LogLevel.Information) //also, try enabling LogLevel.Trace...
                                        .AddProvider(new RollbarLoggerProvider(rollbarConfig))
                                        );

            await builder.Build().RunAsync();
        }
示例#23
0
        /// <summary>
        /// Gets the Rollbar trace listener configuration.
        /// </summary>
        /// <returns>RollbarConfig.</returns>
        private IRollbarLoggerConfig?GetRollbarTraceListenerConfig()
        {
            if (string.IsNullOrWhiteSpace(this.Attributes[RollbarTraceListenerAttributes.rollbarAccessToken.ToString()]))
            {
                return(null);
            }

            if (!RollbarInfrastructure.Instance.IsInitialized)
            {
#if !NETFX_47nOlder
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")))
                {
                    // We are running within Blazor WASM runtime environment that is known to be single threaded in its nature
                    // at least at the moment, so no background threads are allowed and our infrastructure depends on the threads.
                    // Hence, we can not initialize the infrastructure:
                    // NO-OP...
                    return(null);
                }
#endif

                // It is safe to assume we can use the infrastructure:
                RollbarInfrastructureConfig rollbarInfrastructureConfig = new RollbarInfrastructureConfig(
                    this.Attributes[RollbarTraceListenerAttributes.rollbarAccessToken.ToString()],
                    this.Attributes[RollbarTraceListenerAttributes.rollbarEnvironment.ToString()]
                    );
                RollbarInfrastructure.Instance.Init(rollbarInfrastructureConfig);
                return(rollbarInfrastructureConfig.RollbarLoggerConfig);
            }
            else
            {
                RollbarLoggerConfig rollbarLoggerConfig = new RollbarLoggerConfig(
                    this.Attributes[RollbarTraceListenerAttributes.rollbarAccessToken.ToString()],
                    this.Attributes[RollbarTraceListenerAttributes.rollbarEnvironment.ToString()]
                    );
                return(rollbarLoggerConfig);
            }
        }
        public void LongReportIsAsync()
        {
            const int maxCallLengthInMillisec = 50;
            TimeSpan  payloadSubmissionDelay  = TimeSpan.FromMilliseconds(3 * maxCallLengthInMillisec);

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();

            payloadManipulationOptions.Transform = delegate
            {
                Thread.Sleep(payloadSubmissionDelay);
            };
            loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);

            using IRollbar logger = RollbarFactory.CreateNew().Configure(loggerConfig);
            try
            {
                this.IncrementCount <CommunicationEventArgs>();
                Stopwatch sw = Stopwatch.StartNew();
                logger.Log(ErrorLevel.Error, "test message");
                sw.Stop();
                Assert.IsTrue(sw.ElapsedMilliseconds < maxCallLengthInMillisec);
                Thread.Sleep(payloadSubmissionDelay);
            }
            catch
            {
                Assert.Fail("should never get here!");
            }
        }
        public void TimeoutExceptionAggregatesMisconfigurationDetails()
        {
            RollbarQueueController.Instance.InternalEvent += Instance_InternalEvent;

            RollbarLoggerConfig badConfig = new RollbarLoggerConfig("MISCONFIGURED_TOKEN"); // this is clearly wrong token...

            using (IRollbar logger = RollbarFactory.CreateNew(badConfig))
            {
                try
                {
                    var badData = new Data(new Body("Misconfigured Person data"));
                    badData.Person = new Person();
                    logger.AsBlockingLogger(TimeSpan.FromSeconds(3)).Log(badData);
                    Assert.Fail("No TimeoutException!");
                }
                catch (TimeoutException ex)
                {
                    Assert.AreEqual("Posting a payload to the Rollbar API Service timed-out", ex.Message);
                    Assert.IsNotNull(ex.InnerException);
                    Assert.IsTrue(ex.InnerException is AggregateException);
                    Assert.IsTrue((ex.InnerException as AggregateException).InnerExceptions.Count > 0);
                }
            }
        }
        public void ConvenienceMethodsUseAppropriateErrorLevels(ErrorLevel expectedLogLevel)
        {
            var awaitAsyncSend  = new ManualResetEventSlim(false);
            var acctualLogLevel = ErrorLevel.Info;

            void Transform(Payload payload)
            {
                acctualLogLevel = payload.Data.Level.Value;
                awaitAsyncSend.Set();
            }

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();

            payloadManipulationOptions.Transform = Transform;
            loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);

            this.IncrementCount <CommunicationEventArgs>();
            using (var logger = RollbarFactory.CreateNew().Configure(loggerConfig))
            {
                try
                {
                    //TODO: implement and add SynchronousPackage around the payload object!!!
                    var ex = new Exception();
                    switch (expectedLogLevel)
                    {
                    case ErrorLevel.Critical:
                        logger.Critical(ex);
                        break;

                    case ErrorLevel.Error:
                        logger.Error(ex);
                        break;

                    case ErrorLevel.Warning:
                        logger.Warning(ex);
                        break;

                    case ErrorLevel.Info:
                        logger.Info(ex);
                        break;

                    case ErrorLevel.Debug:
                        logger.Debug(ex);
                        break;
                    }
                }
                catch
                {
                    Assert.Fail("should never reach here!");
                }
            }

            awaitAsyncSend.Wait();
            Assert.AreEqual(expectedLogLevel, acctualLogLevel);
        }
示例#27
0
        /// <summary>
        /// Enqueues the data.
        /// </summary>
        /// <param name="dataObject">The data object.</param>
        /// <param name="level">The level.</param>
        /// <param name="custom">The custom.</param>
        /// <param name="timeout">The timeout.</param>
        /// <param name="signal">The signal.</param>
        /// <returns>PayloadBundle.</returns>
        internal PayloadBundle?EnqueueData(
            object dataObject,
            ErrorLevel level,
            IDictionary <string, object?>?custom,
            TimeSpan?timeout     = null,
            SemaphoreSlim?signal = null
            )
        {
            // here is the last chance to decide if we need to actually send this payload
            // based on the current config settings and rate-limit conditions:
            if (string.IsNullOrWhiteSpace(this._config.RollbarDestinationOptions.AccessToken) ||
                !this._config.RollbarDeveloperOptions.Enabled ||
                (level < this._config.RollbarDeveloperOptions.LogLevel) ||
                ((this._payloadQueue.AccessTokenQueuesMetadata != null) && this._payloadQueue.AccessTokenQueuesMetadata.IsTransmissionSuspended)
                )
            {
                // nice shortcut:
                return(null);
            }

            if (this._config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting)
            {
                System.Exception?exception = dataObject as System.Exception;
                if (exception == null &&
                    dataObject is Data data &&
                    data.Body != null
                    )
                {
                    exception = data.Body.OriginalException;
                }

                if (exception != null)
                {
                    try
                    {
                        // Here we need to create another logger instance with similar config but configured not to re-throw.
                        // This would prevent infinite recursive calls (in case if we used this instance or any re-throwing instance).
                        // Because we will be re-throwing the exception after reporting, let's report it fully-synchronously.
                        // This logic is on a heavy side. But, fortunately, RethrowExceptionsAfterReporting is intended to be
                        // a development time option:
                        var config = new RollbarLoggerConfig();
                        config.Reconfigure(this._config);
                        config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting = false;
                        using var rollbar = RollbarFactory.CreateNew(config);
                        rollbar.AsBlockingLogger(TimeSpan.FromSeconds(1)).Log(level, dataObject, custom);
                    }
                    catch
                    {
                        // In case there was a TimeoutException (or any un-expected exception),
                        // there is nothing we can do here.
                        // We tried our best...
                    }
                    finally
                    {
                        if (exception is AggregateException aggregateException)
                        {
                            exception = aggregateException.Flatten();
                        }
                        ExceptionDispatchInfo.Capture(exception).Throw();
                    }

                    return(null);
                }
            }


            PayloadBundle?payloadBundle = null;

            try
            {
                payloadBundle = CreatePayloadBundle(dataObject, level, custom, timeout, signal);
            }
            catch (System.Exception exception)
            {
                RollbarErrorUtility.Report(
                    this,
                    dataObject,
                    InternalRollbarError.BundlingError,
                    null,
                    exception,
                    payloadBundle
                    );
                return(null);
            }

            try
            {
                this._payloadQueue.Enqueue(payloadBundle);
            }
            catch (System.Exception exception)
            {
                RollbarErrorUtility.Report(
                    this,
                    dataObject,
                    InternalRollbarError.EnqueuingError,
                    null,
                    exception,
                    payloadBundle
                    );
            }

            return(payloadBundle);
        }
        public void QueueRegisterationTest()
        {
            Console.WriteLine($"Unrealeased queues count: {RollbarQueueController.Instance.GetUnReleasedQueuesCount()}");

            // we need to make sure we are starting clean:
            RollbarQueueController.Instance.FlushQueues();
            RollbarQueueController.Instance.Stop(true);
            RollbarQueueController.Instance.Start();
            //while (RollbarQueueController.Instance.GetQueuesCount() > 0)
            //{
            //    Thread.Sleep(TimeSpan.FromMilliseconds(250));
            //}
            Console.WriteLine($"Unreleased queues count: {RollbarQueueController.Instance.GetUnReleasedQueuesCount()}");

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig1 =
                new RollbarLoggerConfig();

            loggerConfig1.RollbarDestinationOptions.Reconfigure(destinationOptions);

            destinationOptions.AccessToken =
                RollbarUnitTestSettings.AccessToken.Replace('0', '1');
            RollbarLoggerConfig loggerConfig2 =
                new RollbarLoggerConfig();

            loggerConfig2.RollbarDestinationOptions.Reconfigure(destinationOptions);

            Console.WriteLine($"Unreleased queues count: {RollbarQueueController.Instance.GetUnReleasedQueuesCount()}");

            Assert.AreNotEqual(loggerConfig1.RollbarDestinationOptions.AccessToken, loggerConfig2.RollbarDestinationOptions.AccessToken);

            int initialCount  = RollbarQueueController.Instance.GetQueuesCount();
            int initialCount1 = RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken);
            int initialCount2 = RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken);

            Assert.AreEqual(initialCount + 0, RollbarQueueController.Instance.GetQueuesCount());
            Assert.AreEqual(initialCount1 + 0,
                            RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
            Assert.AreEqual(initialCount2 + 0,
                            RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));

            using (var logger1 = RollbarFactory.CreateNew().Configure(loggerConfig1))
            {
                Assert.AreEqual(initialCount + 1, RollbarQueueController.Instance.GetQueuesCount());
                Assert.AreEqual(initialCount1 + 1,
                                RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                Assert.AreEqual(initialCount2 + 0,
                                RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));

                using (var logger2 = RollbarFactory.CreateNew().Configure(loggerConfig1))
                {
                    Assert.AreEqual(initialCount + 2, RollbarQueueController.Instance.GetQueuesCount());
                    Assert.AreEqual(initialCount1 + 2,
                                    RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                    Assert.AreEqual(initialCount2 + 0,
                                    RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));

                    using (var logger3 = RollbarFactory.CreateNew().Configure(loggerConfig2))
                    {
                        Assert.AreEqual(initialCount + 3, RollbarQueueController.Instance.GetQueuesCount());
                        Assert.AreEqual(initialCount1 + 2,
                                        RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                        Assert.AreEqual(initialCount2 + 1,
                                        RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));
                    }

                    // an unused queue does not get removed immediately (but eventually) - so let's wait for it for a few processing cycles:
                    while ((initialCount + 2) != RollbarQueueController.Instance.GetQueuesCount())
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(250));
                    }

                    // if everything is good, we should get here way before this test method times out:
                    Assert.AreEqual(initialCount + 2, RollbarQueueController.Instance.GetQueuesCount());
                    Assert.AreEqual(initialCount1 + 2,
                                    RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                    Assert.AreEqual(initialCount2 + 0,
                                    RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));
                }

                // an unused queue does not get removed immediately (but eventually) - so let's wait for it for a few processing cycles:
                while ((initialCount + 1) != RollbarQueueController.Instance.GetQueuesCount())
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(250));
                }

                // if everything is good, we should get here way before this test method times out:
                Assert.AreEqual(initialCount + 1, RollbarQueueController.Instance.GetQueuesCount());
                Assert.AreEqual(initialCount1 + 1,
                                RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
                Assert.AreEqual(initialCount2 + 0,
                                RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));
            }

            // an unused queue does not get removed immediately (but eventually) - so let's wait for it for a few processing cycles:
            while ((initialCount + 0) != RollbarQueueController.Instance.GetQueuesCount())
            {
                Console.WriteLine($"Unreleased queues count: {RollbarQueueController.Instance.GetUnReleasedQueuesCount()}");
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
            }


            // if everything is good, we should get here way before this test method times out:
            Assert.AreEqual(initialCount + 0, RollbarQueueController.Instance.GetQueuesCount());
            Assert.AreEqual(initialCount1 + 0,
                            RollbarQueueController.Instance.GetQueuesCount(loggerConfig1.RollbarDestinationOptions.AccessToken));
            Assert.AreEqual(initialCount2 + 0,
                            RollbarQueueController.Instance.GetQueuesCount(loggerConfig2.RollbarDestinationOptions.AccessToken));
        }
        public void TestRollbarConfigEqualityMethod()
        {
            RollbarDestinationOptions destinationOptions = new RollbarDestinationOptions("12345", "env1");
            RollbarLoggerConfig       rConfig            = new RollbarLoggerConfig();

            rConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            // test the same config instance references:
            Assert.IsTrue(rConfig.Equals(rConfig), "Same instances are always equal.");

            destinationOptions = new RollbarDestinationOptions("12345", "env1"); // same as rConfig...
            RollbarLoggerConfig rConfigSimilar = new RollbarLoggerConfig();

            rConfigSimilar.RollbarDestinationOptions.Reconfigure(destinationOptions);


            destinationOptions = new RollbarDestinationOptions("12345", "env2");
            RollbarLoggerConfig rConfigOneDiff = new RollbarLoggerConfig();

            destinationOptions = new RollbarDestinationOptions("02345", "env1");
            RollbarLoggerConfig rConfigAnotherDiff = new RollbarLoggerConfig();

            destinationOptions = new RollbarDestinationOptions("02345", "env2");
            RollbarLoggerConfig rConfigTwoDiffs = new RollbarLoggerConfig();

            destinationOptions = new RollbarDestinationOptions("12345", null);
            RollbarLoggerConfig rConfigOneNullifed = new RollbarLoggerConfig();

            // test different config instances simple properties:
            Assert.IsTrue(rConfig.Equals(rConfigSimilar), "Simple properties: Similar instances are always equal.");
            Assert.IsFalse(rConfig.Equals(rConfigOneDiff), "Simple properties: One different property value makes unequal.");
            Assert.IsFalse(rConfig.Equals(rConfigAnotherDiff), "Simple properties: Another different property value makes unequal.");
            Assert.IsFalse(rConfig.Equals(rConfigTwoDiffs), "Simple properties: Multiple different property values make unequal.");
            Assert.IsFalse(rConfig.Equals(rConfigOneNullifed), "Simple properties: Nullified property of one config instance makes unequal.");

            // test structured/complex properties:
            Person person = new Person()
            {
                UserName = "******", Email = "*****@*****.**",
            };
            Person personSimilar = new Person()
            {
                UserName = "******", Email = "*****@*****.**",
            };
            Person personOneDiff = new Person()
            {
                UserName = "******", Email = "*****@*****.**",
            };
            Person personOneNull = new Person()
            {
                UserName = "******", Email = null,
            };

            RollbarPayloadAdditionOptions additionOptions = new RollbarPayloadAdditionOptions();

            additionOptions.Person = person;
            rConfig.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);
            Assert.IsTrue(rConfig.Equals(rConfig), "Structured properties: Same instances are always equal.");

            additionOptions.Person = person;
            rConfigSimilar.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);
            Assert.IsTrue(rConfig.Equals(rConfigSimilar), "Structured properties: Similar #1 instances are always equal.");

            additionOptions.Person = personSimilar;
            rConfigSimilar.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);
            Assert.IsTrue(rConfig.Equals(rConfigSimilar), "Structured properties: Similar #2 instances are always equal.");

            additionOptions.Person = personOneDiff;
            rConfigSimilar.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);
            Assert.IsFalse(rConfig.Equals(rConfigSimilar), "Structured properties: One different property value makes unequal.");

            additionOptions.Person = personOneNull;
            rConfigSimilar.RollbarPayloadAdditionOptions.Reconfigure(additionOptions);
            Assert.IsFalse(rConfig.Equals(rConfigSimilar), "Structured properties: Nullified property of one config instance makes unequal.");
        }
        public void ScopedInstanceTest()
        {
            // we need to make sure we are starting clean:
            RollbarQueueController.Instance.FlushQueues();
            RollbarQueueController.Instance.Start();
            var accessTokenQueues =
                RollbarQueueController.Instance.GetQueues(RollbarUnitTestSettings.AccessToken);

            while (accessTokenQueues.Any())
            {
                string msg = "Initial queues count: " + accessTokenQueues.Count();
                System.Diagnostics.Trace.WriteLine(msg);
                Console.WriteLine(msg);
                foreach (var queue in accessTokenQueues)
                {
                    msg = "---Payloads in a queue: " + queue.GetPayloadCount();
                    System.Diagnostics.Trace.WriteLine(msg);
                    Console.WriteLine(msg);

                    if (!queue.IsReleased)
                    {
                        queue.Release();
                    }
                    else
                    {
                        queue.Flush();
                    }
                }
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
                accessTokenQueues =
                    RollbarQueueController.Instance.GetQueues(RollbarUnitTestSettings.AccessToken);
            }

            RollbarDestinationOptions destinationOptions =
                new RollbarDestinationOptions(
                    RollbarUnitTestSettings.AccessToken,
                    RollbarUnitTestSettings.Environment
                    );
            RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();

            loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);

            int totalInitialQueues = RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);

            using (var logger = RollbarFactory.CreateNew().Configure(loggerConfig))
            {
                Assert.AreEqual(totalInitialQueues + 1, RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken));
                this.IncrementCount <CommunicationEventArgs>();
                logger.Log(ErrorLevel.Error, "test message");
            }
            // an unused queue does not get removed immediately (but eventually) - so let's wait for it for a few processing cycles:
            int currentQueuesCount =
                RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);

            while (totalInitialQueues != currentQueuesCount)
            {
                string msg = "Current queues count: " + currentQueuesCount + " while initial count was: " + totalInitialQueues;
                System.Diagnostics.Trace.WriteLine(msg);
                Console.WriteLine(msg);
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
                currentQueuesCount =
                    RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);
            }

            // if everything is good, we should get here way before this test method times out:
            Assert.AreEqual(totalInitialQueues, RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken));
        }