Пример #1
0
 public static IHostBuilder CreateHostBuilder() =>
 new HostBuilder()
 .ConfigureLogging(builder => builder.ClearProviders())
 .ConfigureServices(services =>
 {
     // We don't care much about which options we are setting.
     // These are for testing that all the extension method overloads work as expected.
     services.AddGoogleDiagnostics(
         new TraceServiceOptions
     {
         ProjectId = ProjectId,
         Options   = TraceOptions.Create(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate))
     },
         new LoggingServiceOptions
     {
         ProjectId   = ProjectId,
         ServiceName = Service,
         Version     = Version,
         Options     = LoggingOptions.Create(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate))
     },
         new ErrorReportingServiceOptions
     {
         ProjectId   = ProjectId,
         ServiceName = Service,
         Version     = Version,
         Options     = ErrorReportingOptions.CreateInstance(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate))
     });
 });
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            if (Configuration["Google:EnableTrace"] == "True")
            {
                Console.WriteLine("adding google trace!");
                services.AddGoogleTrace(
                    options =>
                {
                    options.ProjectId = Configuration["Google:ProjectId"];
                    options.Options   = TraceOptions.Create(
                        bufferOptions: BufferOptions.TimedBuffer(TimeSpan.FromSeconds(5.5)),
                        qpsSampleRate: 1D,
                        retryOptions: RetryOptions.NoRetry(ExceptionHandling.Ignore)
                        );
                    options.TraceFallbackPredicate = TraceDecisionPredicate.Create(request =>
                    {
                        // Do not trace OPTIONS
                        var isOptionsCall = request.Method.ToLowerInvariant().Equals("options");

                        // Do not trace our monitoring routes
                        var isMonitoringRoute =
                            request.Path.Equals(PathString.FromUriComponent("/"));

                        return(!(isOptionsCall || isMonitoringRoute));
                    });
                });
            }

            services.AddHttpClient <IGetStuffService, GetStuffService>();
        }
        private IWebHostBuilder GetExceptionPropagatingHostBuilder()
        {
#if NETCOREAPP2_0
            string projectId = LoggingTestApplicationPropagateExceptions.ProjectId;
            // Sample: RegisterGoogleLoggerPropagateExceptions2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Explicitly create logger options that will propagate any exceptions thrown
                // during logging.
                RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
                // Also set the no buffer option so that writing the logs is attempted inmediately.
                BufferOptions bufferOptions = BufferOptions.NoBuffer();
                LoggerOptions loggerOptions = LoggerOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);

                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId, options: loggerOptions));
            })
                   .UseStartup <Startup>());

            // End sample
#else
            return(new WebHostBuilder().UseStartup <LoggingTestApplicationPropagateExceptions>());
#endif
        }
Пример #4
0
        public void NoRetry()
        {
            RetryOptions options = RetryOptions.NoRetry();

            Assert.Equal(RetryType.None, options.RetryType);
            Assert.Equal(ExceptionHandling.Ignore, options.ExceptionHandling);
        }
Пример #5
0
        public void GetConsumer_InvalidOptions()
        {
            BufferOptions bufferOptions = new BufferOptions((BufferType)5);
            RetryOptions  retryOptions  = RetryOptions.NoRetry();

            Assert.Throws <ArgumentException>(
                () => ConsumerFactory <int> .GetConsumer(new IntConsumer(), ConstantSizer <int> .GetSize, bufferOptions, retryOptions));
        }
Пример #6
0
        public void GetConsumer_Timed()
        {
            BufferOptions   bufferOptions = BufferOptions.TimedBuffer();
            RetryOptions    retryOptions  = RetryOptions.NoRetry();
            IConsumer <int> consumer      = ConsumerFactory <int> .GetConsumer(new IntConsumer(), ConstantSizer <int> .GetSize, bufferOptions, retryOptions);

            Assert.IsType <TimedBufferingConsumer <int> >(consumer);
        }
Пример #7
0
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="labels">Optional, custom labels to be added to log entries.</param>
 /// <param name="monitoredResource">Optional, the monitored resource.  The monitored resource will
 ///     be automatically detected if it is not set and will default to the global resource if the detection fails.
 ///     See: https://cloud.google.com/logging/docs/api/v2/resource-list </param>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 /// <param name="retryOptions">Optional, the retry options.  Defaults to a <see cref="RetryType.None"/></param>
 public static LoggerOptions Create(LogLevel logLevel = LogLevel.Information,
                                    Dictionary <string, string> labels  = null,
                                    MonitoredResource monitoredResource = null, BufferOptions bufferOptions = null, RetryOptions retryOptions = null)
 {
     labels            = labels ?? new Dictionary <string, string>();
     monitoredResource = monitoredResource ?? MonitoredResourceBuilder.FromPlatform();
     bufferOptions     = bufferOptions ?? BufferOptions.TimedBuffer();
     retryOptions      = retryOptions ?? RetryOptions.NoRetry();
     return(new LoggerOptions(logLevel, labels, monitoredResource, bufferOptions, retryOptions));
 }
Пример #8
0
        public void Receive_NoRetry_Propagate()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) => {
                int[] intArray = { 1, 2, 3, 4 };
                Assert.Throws <RpcException>(() => { retryConsumer.Receive(intArray); });

                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
                Assert.Null(timer.Callback);
            }, RetryOptions.NoRetry(ExceptionHandling.Propagate));
        }
Пример #9
0
        public void GetConsumer_None()
        {
            BufferOptions   bufferOptions = BufferOptions.NoBuffer();
            RetryOptions    retryOptions  = RetryOptions.NoRetry();
            IConsumer <int> consumer      = ConsumerFactory <int> .GetConsumer(new IntConsumer(), ConstantSizer <int> .GetSize, bufferOptions, retryOptions);

            Assert.IsType <RpcRetryConsumer <int> >(consumer);
            var retryConsumer = (RpcRetryConsumer <int>)consumer;

            Assert.IsType <IntConsumer>(retryConsumer._consumer);
        }
Пример #10
0
        public void Receive_NoRetry_Ignore()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);

                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
                Assert.Null(timer.Callback);
            }, RetryOptions.NoRetry());
        }
        private void Troubleshooting()
        {
            // Not a test - just a sample.

            // Sample: Troubleshooting
            // Explicitly create trace options that will propagate any exceptions thrown during tracing.
            RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
            // Also set the no buffer option so that tracing is attempted immediately.
            BufferOptions bufferOptions = BufferOptions.NoBuffer();
            TraceOptions  traceOptions  = TraceOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);
            // End sample
        }
Пример #12
0
        public void Receive()
        {
            var options      = RetryOptions.NoRetry(ExceptionHandling.Propagate);
            var mockConsumer = new Mock <IConsumer <int> >();
            Func <Action, RetryOptions, ISequentialThreadingTimer> timerFactory =
                (callback, retryOptions) => new SequentialThreadingTimer();

            using (var retryConsumer = new RpcRetryConsumer <int>(
                       mockConsumer.Object, options, Utils.ConstantSizer <int> .GetSize, timerFactory))
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);
                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
            }
        }
Пример #13
0
            // Sample: Troubleshooting
            public static IHostBuilder CreateHostBuilder() =>
            new HostBuilder()
            .ConfigureServices(services =>
            {
                // Explicitly create trace options that will propagate any exceptions thrown during tracing.
                RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
                // Also set the no buffer option so that tracing is attempted immediately.
                BufferOptions bufferOptions = BufferOptions.NoBuffer();
                TraceOptions traceOptions   = TraceOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);

                // Replace ProjectId with your Google Cloud Project ID.
                services.AddGoogleTrace(new TraceServiceOptions {
                    ProjectId = ProjectId, Options = traceOptions
                });
                // Register other services here if you need them.
            });
Пример #14
0
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="logName">Optional, the name of the log.  Defaults to 'aspnetcore'.</param>
 /// <param name="labels">Optional, custom labels to be added to log entries.
 /// Keys and values added to <paramref name="labels"/> should not be null.
 /// If they are, an exception will be throw when attempting to log an entry.
 /// The entry won't be logged and the exception will be propagated depending
 /// on the value of <see cref="RetryOptions.ExceptionHandling"/>.</param>
 /// <param name="monitoredResource">Optional, the monitored resource.  The monitored resource will
 /// be automatically detected if it is not set and will default to the global resource if the detection fails.
 /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 /// <param name="retryOptions">Optional, the retry options.  Defaults to a <see cref="RetryType.None"/></param>
 /// <param name="loggerDiagnosticsOutput">Optional. If set some logger diagnostics info will be written
 /// to the given <see cref="TextWriter"/>. Currently the only diagnostics info we provide is the URL where
 /// the logs written with these options can be found.</param>
 public static LoggerOptions Create(
     LogLevel logLevel = LogLevel.Information,
     string logName    = null,
     Dictionary <string, string> labels  = null,
     MonitoredResource monitoredResource = null,
     BufferOptions bufferOptions         = null,
     RetryOptions retryOptions           = null,
     TextWriter loggerDiagnosticsOutput  = null)
 {
     logName           = logName ?? _baseLogName;
     labels            = labels ?? new Dictionary <string, string>();
     monitoredResource = monitoredResource ?? MonitoredResourceBuilder.FromPlatform();
     bufferOptions     = bufferOptions ?? BufferOptions.TimedBuffer();
     retryOptions      = retryOptions ?? RetryOptions.NoRetry();
     return(new LoggerOptions(logLevel, logName, labels, monitoredResource, bufferOptions, retryOptions, loggerDiagnosticsOutput));
 }
 public override void ConfigureServices(IServiceCollection services) =>
 base.ConfigureServices(services
                        .AddGoogleExceptionLogging(options =>
 {
     options.ProjectId   = ProjectId;
     options.ServiceName = EntryData.Service;
     options.Version     = EntryData.Version;
     // This is just so that our validator finds the log entries associated to errors.
     options.Options = ErrorReportingOptions.Create(EventTarget.ForLogging(ProjectId, "aspnetcore"));
 })
                        .AddGoogleTrace(options =>
 {
     options.ProjectId = ProjectId;
     options.Options   = TraceOptions.Create(
         double.PositiveInfinity, BufferOptions.NoBuffer(), RetryOptions.NoRetry(ExceptionHandling.Propagate));
 }));
Пример #16
0
        private static IWebHostBuilder GetExceptionPropagatingHostBuilder()
        {
            string projectId = "non-existent-project-id";
            // Sample: RegisterGoogleLoggerPropagateExceptions
            // Explicitly create logger options that will propagate any exceptions thrown
            // during logging.
            RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
            // Also set the no buffer option so that writing the logs is attempted immediately.
            BufferOptions bufferOptions = BufferOptions.NoBuffer();
            LoggerOptions loggerOptions = LoggerOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);

            return(new WebHostBuilder()
                   .UseGoogleDiagnostics(projectId, loggerOptions: loggerOptions)
                   .UseStartup <Startup>());
            // End sample
        }
 public override void ConfigureServices(IServiceCollection services) =>
 base.ConfigureServices(services
                        .AddGoogleErrorReportingForAspNetCore(new Common.ErrorReportingServiceOptions
 {
     ProjectId   = ProjectId,
     ServiceName = EntryData.Service,
     Version     = EntryData.Version,
     Client      = new LoggingServiceV2ClientBuilder
     {
         TokenAccessMethod = (uri, cancellation) => Task.FromResult("very_bad_token")
     }.Build(),
     // This is just so that our validator finds the log entries associated to errors.
     Options = ErrorReportingOptions.CreateInstance(
         logName: "aspnetcore",
         bufferOptions: BufferOptions.NoBuffer(),
         retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate))
 }));
Пример #18
0
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="logName">Optional, the name of the log.  Defaults to 'aspnetcore'.</param>
 /// <param name="labels">Optional, custom labels to be added to log entries.
 /// Keys and values added to <paramref name="labels"/> should not be null.
 /// If they are, an exception will be throw when attempting to log an entry.
 /// The entry won't be logged and the exception will be propagated depending
 /// on the value of <see cref="RetryOptions.ExceptionHandling"/>.</param>
 /// <param name="monitoredResource">Optional, the monitored resource.  The monitored resource will
 /// be automatically detected if it is not set and will default to the global resource if the detection fails.
 /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 /// <param name="retryOptions">Optional, the retry options.  Defaults to a <see cref="RetryType.None"/></param>
 /// <param name="loggerDiagnosticsOutput">Optional. If set some logger diagnostics info will be written
 /// to the given <see cref="TextWriter"/>. Currently the only diagnostics info we provide is the URL where
 /// the logs written with these options can be found.</param>
 /// <param name="serviceName">A string that represents the version of the service or the source code that logs are written for.
 /// When set, it will be included in the <code>serviceContext</code> field of the log entry JSON payload.</param>
 /// <param name="version">A string that represents the version of the service or the source code that logs are written for.
 /// When set, it will be included in the <code>serviceContext</code> field of the log entry JSON payload.</param>
 public static LoggerOptions CreateWithServiceContext(
     LogLevel logLevel = LogLevel.Information,
     string logName    = null,
     Dictionary <string, string> labels  = null,
     MonitoredResource monitoredResource = null,
     BufferOptions bufferOptions         = null,
     RetryOptions retryOptions           = null,
     TextWriter loggerDiagnosticsOutput  = null,
     string serviceName = null,
     string version     = null)
 {
     logName ??= _baseLogName;
     labels ??= new Dictionary <string, string>();
     monitoredResource ??= MonitoredResourceBuilder.FromPlatform();
     bufferOptions ??= BufferOptions.TimedBuffer();
     retryOptions ??= RetryOptions.NoRetry();
     return(new LoggerOptions(logLevel, logName, labels, monitoredResource, bufferOptions, retryOptions, loggerDiagnosticsOutput, serviceName, version));
 }
Пример #19
0
        private static IHostBuilder GetExceptionPropagatingHostBuilder()
        {
            string projectId = "non-existent-project-id";

            // Sample: RegisterGoogleLoggerPropagateExceptions_Core3
            // Explicitly create logger options that will propagate any exceptions thrown
            // during logging.
            RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
            // Also set the no buffer option so that writing the logs is attempted immediately.
            BufferOptions bufferOptions = BufferOptions.NoBuffer();
            LoggerOptions loggerOptions = LoggerOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);
            var           hostBuilder   = Host.CreateDefaultBuilder()
                                          .ConfigureWebHostDefaults(webBuilder => webBuilder
                                                                    // Replace projectId with your Google Cloud Project ID.
                                                                    .UseGoogleDiagnostics(projectId, loggerOptions: loggerOptions)
                                                                    .UseStartup <Startup>());

            // End sample
            return(hostBuilder.ConfigureWebHost(webBuilder => webBuilder.UseTestServer()));
        }
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            // Explicitly create logger options that will propagate any exceptions thrown
            // during logging.
            RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
            // Also set the no buffer option so that writing the logs is attempted inmediately.
            BufferOptions bufferOptions = BufferOptions.NoBuffer();
            LoggerOptions loggerOptions = LoggerOptions.Create(retryOptions: retryOptions, bufferOptions: bufferOptions);

            // Replace ProjectId with your Google Cloud Project ID.
            loggerFactory.AddGoogle(app.ApplicationServices, ProjectId, options: loggerOptions);

            // ...any other configuration your application requires.

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 public override void ConfigureServices(IServiceCollection services) =>
 base.ConfigureServices(services
                        .AddGoogleTraceForAspNetCore(new AspNetCoreTraceOptions
 {
     ServiceOptions = new Common.TraceServiceOptions
     {
         ProjectId = ProjectId,
         Options   = TraceOptions.Create(
             double.PositiveInfinity, BufferOptions.NoBuffer(), RetryOptions.NoRetry(ExceptionHandling.Propagate))
     }
 })
                        .AddGoogleErrorReportingForAspNetCore(new Common.ErrorReportingServiceOptions
 {
     ProjectId   = ProjectId,
     ServiceName = EntryData.Service,
     Version     = EntryData.Version,
     // This is just so that our validator finds the log entries associated to errors.
     Options = ErrorReportingOptions.CreateInstance(
         logName: "aspnetcore",
         bufferOptions: BufferOptions.NoBuffer(),
         retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate))
 }));
Пример #22
0
            // Sample: PropagatesExceptions
            public static IHostBuilder CreateHostBuilder() =>
            new HostBuilder()
            .ConfigureServices(services =>
            {
                //Explicitly create logger options that will propagate any exceptions thrown
                // during logging.
                RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
                // Also set the no buffer option so that writing the logs is attempted immediately.
                BufferOptions bufferOptions = BufferOptions.NoBuffer();

                // Replace ProjectId with your Google Cloud Project ID.
                services.AddLogging(builder => builder.AddGoogle(new LoggingServiceOptions
                {
                    // Replace ProjectId with your Google Cloud Project ID.
                    ProjectId = ProjectId,
                    // Replace Service with a name or identifier for the service.
                    ServiceName = Service,
                    // Replace Version with a version for the service.
                    Version = Version,
                    Options = LoggingOptions.Create(retryOptions: retryOptions, bufferOptions: bufferOptions)
                }));;
                // Register other services here if you need them.
            });
Пример #23
0
 public void GetConsumer_InvalidOptions_Null()
 {
     Assert.Throws <ArgumentNullException>(
         () => ConsumerFactory <int> .GetConsumer(new IntConsumer(), ConstantSizer <int> .GetSize, null, RetryOptions.NoRetry()));
 }
Пример #24
0
 public void GetConsumer_InvalidConsumer_Null()
 {
     Assert.Throws <ArgumentNullException>(
         () => ConsumerFactory <int> .GetConsumer(null, ConstantSizer <int> .GetSize, BufferOptions.TimedBuffer(), RetryOptions.NoRetry()));
 }
Пример #25
0
 public void GetConsumer_InvalidSizer_Null()
 {
     Assert.Throws <ArgumentNullException>(
         () => ConsumerFactory <int> .GetConsumer(new IntConsumer(), null, BufferOptions.SizedBuffer(), RetryOptions.NoRetry()));
 }
Пример #26
0
 public override RetryOptions GetRetryOptions() => RetryOptions.NoRetry(ExceptionHandling.Propagate);
Пример #27
0
        public async Task UseGoogleDiagnostics_ValidateDependencyInjection()
        {
            var testId    = IdGenerator.FromDateTime();
            var startTime = DateTime.UtcNow;

            var hostBuilder = GetHostBuilder(webHostBuilder =>
                                             webHostBuilder
                                             .UseDefaultServiceProvider(options => options.ValidateScopes = true)
                                             .ConfigureServices(services =>
                                                                services.AddGoogleDiagnosticsForAspNetCore(
                                                                    TestEnvironment.GetTestProjectId(), EntryData.Service, EntryData.Version,
                                                                    traceOptions: TraceOptions.Create(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate)),
                                                                    loggingOptions: LoggingOptions.Create(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate)),
                                                                    errorReportingOptions: ErrorReportingOptions.CreateInstance(retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate)))));

            using var server = GetTestServer(hostBuilder);
            using var client = server.CreateClient();
            await TestTrace(testId, startTime, client);
            await TestLogging(testId, startTime, client);
            await TestErrorReporting(testId, client);
        }
        public void Log_ThrowsIfNullLabels_RetryOptionsPropagateExceptions()
        {
            var mockServiceProvider = new Mock <IServiceProvider>();

            mockServiceProvider.Setup(sp => sp.GetService(typeof(IEnumerable <ILogEntryLabelProvider>)))
            .Returns(new ILogEntryLabelProvider[] { new EmptyLogEntryLabelProvider() });

            var mockConsumer = new Mock <IConsumer <LogEntry> >();
            var logger       = GetLogger(mockConsumer.Object, LogLevel.Information, serviceProvider: mockServiceProvider.Object, logName: BaseLogName, retryOptions: RetryOptions.NoRetry(ExceptionHandling.Propagate));

            Assert.Throws <ArgumentNullException>(() => logger.LogInformation(LogMessage));
            mockConsumer.Verify(c => c.Receive(It.IsAny <IEnumerable <LogEntry> >()), Times.Never);
        }