コード例 #1
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            SetupRoutes(app);
            LoggerOptions loggerOptions = LoggerOptions.Create(LogLevel.Error);

            loggerFactory.AddGoogle(ProjectId, loggerOptions);
        }
コード例 #2
0
        private static void ConfigureGoogleDiagnosticsServices(
            IServiceCollection services,
            string projectId,
            string serviceName,
            string serviceVersion,
            LoggerOptions loggerOptions,
            TraceOptions traceOptions,
            ErrorReportingOptions errorReportingOptions)
        {
            projectId = Project.GetAndCheckProjectId(projectId, null);

            services.AddLogEntryLabelProvider <TraceIdLogEntryLabelProvider>();
            services.AddGoogleTraceForAspNetCore(new AspNetCoreTraceOptions
            {
                ServiceOptions = new Common.TraceServiceOptions
                {
                    ProjectId = projectId,
                    Options   = traceOptions
                }
            });
            services.AddGoogleErrorReportingForAspNetCore(new Common.ErrorReportingServiceOptions
            {
                ProjectId   = projectId,
                ServiceName = serviceName,
                Version     = serviceVersion,
                Options     = errorReportingOptions
            });

            loggerOptions = loggerOptions ?? LoggerOptions.Create();
            loggerOptions.CommonLoggerOptions.ProjectId = projectId;
            services.AddLogging(builder => builder.AddGoogle(loggerOptions.CommonLoggerOptions));
        }
コード例 #3
0
 /// <summary>
 /// Create an <see cref="ILoggerProvider"/> for Google Stackdriver Logging.
 /// </summary>
 /// <param name="serviceProvider">The service provider to resolve additional services from.
 /// May be null, in which case additional services (such as custom labels) will not be used.</param>
 /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine.
 ///     The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be
 ///     detected from the platform.</param>
 /// <param name="options">Optional, options for the logger.</param>
 /// <param name="client">Optional, logging client.</param>
 public static GoogleLoggerProvider Create(IServiceProvider serviceProvider, string projectId = null,
                                           LoggerOptions options = null, LoggingServiceV2Client client = null)
 {
     options   = options ?? LoggerOptions.Create();
     projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource);
     return(Create(LogTarget.ForProject(projectId), serviceProvider, options, client));
 }
コード例 #4
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            SetupRoutes(app);
            LoggerOptions loggerOptions = LoggerOptions.Create(LogLevel.Warning, null, BufferOptions.NoBuffer());

            loggerFactory.AddGoogle(ProjectId, loggerOptions);
        }
コード例 #5
0
        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
        }
コード例 #6
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
#pragma warning disable CS0618 // Type or member is obsolete - loggerFactory.AddConsole. We need to work out how to do all this better.
            if (UseStackdriverLogging)
            {
                var platform      = Platform.Instance();
                var loggerOptions = LoggerOptions.Create(
                    logLevel: LogLevel,
                    logName: LogId ?? platform.GkeDetails?.ContainerName ?? "aspnetcore");
                loggerFactory.AddGoogle(app.ApplicationServices, platform.ProjectId, loggerOptions);
                if (IncludeConsoleLogging)
                {
                    loggerFactory.AddConsole();
                }
            }
            else
            {
                // If we're not logging to Stackdriver, use console logging instead.
                loggerFactory.AddConsole();
                loggerFactory.AddDebug();
#pragma warning restore CS0618 // Type or member is obsolete
            }

            if (UseStackdriverErrorReporting)
            {
                app.UseGoogleExceptionLogging();
            }
        }
コード例 #7
0
        public async Task UseGoogleDiagnostics_ConfiguresComponents()
        {
            var testId    = IdGenerator.FromDateTime();
            var startTime = DateTime.UtcNow;
            var resource  = new MonitoredResource
            {
                Type   = "global",
                Labels =
                {
                    { "project_id", TestEnvironment.GetTestProjectId() },
                    { "module_id",  EntryData.Service                  },
                    { "version_id", EntryData.Version                  },
                    { "build_id",   "some-build-id"                    }
                }
            };
            // We won't be able to detect the right monitored resource, so specify it explicitly.
            var loggerOptions  = LoggerOptions.Create(monitoredResource: resource);
            var webHostBuilder = new WebHostBuilder()
                                 .ConfigureServices(services => services.AddMvcCore())
                                 .Configure(app => app.UseMvcWithDefaultRoute())
                                 .UseGoogleDiagnostics(TestEnvironment.GetTestProjectId(), EntryData.Service, EntryData.Version, loggerOptions);

            using (var server = new TestServer(webHostBuilder))
                using (var client = server.CreateClient())
                {
                    await TestTrace(testId, startTime, client);
                    await TestLogging(testId, startTime, client);
                    await TestErrorReporting(testId, client);
                }
        }
コード例 #8
0
 public static ILoggerFactory AddGoogle(this ILoggerFactory factory, IServiceProvider serviceProvider, string projectId = null,
                                        LoggerOptions options = null, LoggingServiceV2Client client = null)
 {
     GaxPreconditions.CheckNotNull(factory, nameof(factory));
     options   = options ?? LoggerOptions.Create();
     projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource);
     return(factory.AddGoogle(LogTarget.ForProject(projectId), serviceProvider, options, client));
 }
コード例 #9
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            SetupRoutes(app);
            var           options       = BufferOptions.TimedBuffer(TimeSpan.FromSeconds(20));
            LoggerOptions loggerOptions = LoggerOptions.Create(LogLevel.Warning, null, options);

            loggerFactory.AddGoogle(ProjectId, loggerOptions);
        }
コード例 #10
0
ファイル: GoogleLoggerTest.cs プロジェクト: greggaba/GCDotNet
        private GoogleLogger GetLogger(
            IConsumer <LogEntry> consumer, LogLevel logLevel = LogLevel.Information,
            Dictionary <string, string> labels = null)
        {
            LoggerOptions options = LoggerOptions.Create(logLevel, labels, MonitoredResourceBuilder.GlobalResource);

            return(new GoogleLogger(consumer, s_logTarget, options, _logName, s_clock));
        }
コード例 #11
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            SetupRoutes(app);
            LoggerOptions loggerOptions = LoggerOptions.Create(
                LogLevel.Error, null, null, null, BufferOptions.SizedBuffer());

            loggerFactory.AddGoogle(app.ApplicationServices, ProjectId, loggerOptions);
        }
コード例 #12
0
        private static IWebHostBuilder GetUrlWriterHostBuilder()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLoggerWriteUrl
            return(new WebHostBuilder()
                   .UseGoogleDiagnostics(projectId, loggerOptions: LoggerOptions.Create(loggerDiagnosticsOutput: Console.Out))
                   .UseStartup <Startup>());
            // End sample
        }
コード例 #13
0
        private GoogleLogger GetLogger(
            IConsumer <LogEntry> consumer, LogLevel logLevel = LogLevel.Information,
            Dictionary <string, string> labels = null, IServiceProvider serviceProvider = null,
            string logName            = null,
            RetryOptions retryOptions = null)
        {
            LoggerOptions options = LoggerOptions.Create(logLevel, logName, labels, MonitoredResourceBuilder.GlobalResource, retryOptions: retryOptions);

            return(new GoogleLogger(consumer, s_logTarget, options, _logName, s_clock, serviceProvider));
        }
コード例 #14
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var labels = new Dictionary <string, string> {
                { "some-key", "some-value" }
            };

            SetupRoutes(app);
            LoggerOptions loggerOptions = LoggerOptions.Create(
                LogLevel.Warning, null, labels, null, BufferOptions.NoBuffer());

            loggerFactory.AddGoogle(app.ApplicationServices, ProjectId, loggerOptions);
        }
コード例 #15
0
        /// <summary>
        /// Create an <see cref="ILoggerProvider"/> for Google Stackdriver Logging.
        /// </summary>
        /// <param name="logTarget">Where to log to. Must not be null.</param>
        /// <param name="serviceProvider">Optional, the service provider to resolve additional services from. May be null,
        /// in which case additional services (such as custom labels) will not be used.</param>
        /// <param name="options">Optional, options for the logger.</param>
        /// <param name="client">Optional, logging client.</param>
        public static GoogleLoggerProvider Create(LogTarget logTarget, IServiceProvider serviceProvider,
                                                  LoggerOptions options = null, LoggingServiceV2Client client = null)
        {
            // Check params and set defaults if unset.
            GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget));
            client  = client ?? LoggingServiceV2Client.Create();
            options = options ?? LoggerOptions.Create();

            // Get the proper consumer from the options and add a logger provider.
            IConsumer <LogEntry> consumer = LogConsumer.Create(client, options.BufferOptions, options.RetryOptions);

            return(new GoogleLoggerProvider(consumer, logTarget, options, serviceProvider));
        }
コード例 #16
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Main}/{action=Index}/{id}");
            });
            LoggerOptions loggerOptions = LoggerOptions.Create(
                LogLevel.Warning, null, null, null, BufferOptions.NoBuffer());

            loggerFactory.AddGoogle(app.ApplicationServices, _projectId, loggerOptions);
        }
コード例 #17
0
        private GoogleLogger GetLogger(
            IConsumer <LogEntry> consumer      = null, LogLevel logLevel = LogLevel.Information,
            Dictionary <string, string> labels = null, IServiceProvider serviceProvider = null,
            string logName = null,
            MonitoredResource monitoredResource = null, LogTarget logTarget = null,
            RetryOptions retryOptions           = null)
        {
            consumer          = consumer ?? new Mock <IConsumer <LogEntry> >(MockBehavior.Strict).Object;
            monitoredResource = monitoredResource ?? MonitoredResourceBuilder.GlobalResource;
            logTarget         = logTarget ?? s_defaultLogTarget;
            LoggerOptions options = LoggerOptions.Create(logLevel, logName, labels, monitoredResource, retryOptions: retryOptions);

            return(new GoogleLogger(consumer, logTarget, options, LogName, s_clock, serviceProvider));
        }
コード例 #18
0
        /// <summary>
        /// Adds a <see cref="GoogleLoggerProvider"/> for <see cref="GoogleLogger"/>s.
        /// </summary>
        /// <param name="builder">The logger builder. Cannot be null.</param>
        /// <param name="serviceProvider">The service provider to resolve additional services from.</param>
        /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine.
        ///     The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be
        ///     detected from the platform.</param>
        /// <param name="options">Optional, options for the logger.</param>
        /// <param name="client">Optional, logging client.</param>
        public static void AddGoogle(this ILoggingBuilder builder,
                                     IServiceProvider serviceProvider,
                                     string projectId              = null,
                                     LoggerOptions options         = null,
                                     LoggingServiceV2Client client = null)
        {
            GaxPreconditions.CheckNotNull(builder, nameof(builder));

            options   = options ?? LoggerOptions.Create();
            projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource);
            LogTarget logTarget = LogTarget.ForProject(projectId);

            var provider = GoogleLoggerProvider.Create(serviceProvider, projectId, options, client);

            builder.Services.AddSingleton <ILoggerProvider>(provider);
        }
コード例 #19
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
        }
コード例 #20
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            // Once created, the GoogleLogger will write the URL where logs can be found
            // to a given System.IO.TextWriter, for instance System.Console.Out.
            LoggerOptions loggerOptions = LoggerOptions.Create(loggerDiagnosticsOutput: Console.Out);

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

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

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #21
0
        private IWebHostBuilder GetUrlWriterHostBuilder()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLoggerWriteUrl2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Once created, the GoogleLogger will write the URL where logs can be found
                // to a given System.IO.TextWriter, for instance System.Console.Out.
                LoggerOptions loggerOptions = LoggerOptions.Create(loggerDiagnosticsOutput: Console.Out);

                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId, loggerOptions));
            })
                   .UseStartup <Startup>());
            // End sample
        }
コード例 #22
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()));
        }
コード例 #23
0
        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?}");
            });
        }
コード例 #24
0
        static async Task MainAsync(string[] args)
        {
            InitializeGoogleCloudSdk();

            Encoding.RegisterProvider(UTF8EncodingProvider.Default);

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddGoogle(Options.GoogleCloudProjectId, LoggerOptions.Create(LogLevel.Warning));

            var dbContextFactory = new ApplicationDbContextFactory();

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                (a, b, c, d) => true);

            var source = new CancellationTokenSource();

            Console.CancelKeyPress += (sender, e) =>
            {
                source.Cancel();
            };

            using (var dbContext = dbContextFactory.CreateDbContext())
            {
                await dbContext.Database.MigrateAsync(source.Token);
            }

            var subCommand = args.FirstOrDefault();

            for (; ;)
            {
                switch (subCommand)
                {
                case "hatenabloggroup":
                case "0":
                    await CrawlHatenaBlogGroupAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "hatenablog":
                case "1":
                    await CrawlHatenaBlogAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "hatenablogentry":
                case "2":
                    await CrawlHatenaBlogEntryAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "amazon":
                case "3":
                    await CrawlAmazonAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "calculate":
                case "4":
                    await CalculateScoreAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "exportjson":
                case "5":
                    await ExportJsonAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "uploadjson":
                case "6":
                    await UploadJsonAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                case "backup":
                case "7":
                    await BackupDatabaseAsync(loggerFactory, source.Token);

                    return;

                case "requestbuild":
                case "8":
                    await RequestBuildAsync(loggerFactory, source.Token);

                    return;

                case "cleanbackup":
                case "9":
                    await CleanBackupAsync(loggerFactory, source.Token);

                    return;

                case "executeall":
                case "10":
                    await ExecuteAllAsync(dbContextFactory, loggerFactory, source.Token);

                    return;

                default:
                    Console.WriteLine("[0] hatenabloggroup");
                    Console.WriteLine("[1] hatenablog");
                    Console.WriteLine("[2] hatenablogentry");
                    Console.WriteLine("[3] amazon");
                    Console.WriteLine("[4] calculate");
                    Console.WriteLine("[5] exportjson");
                    Console.WriteLine("[6] uploadjson");
                    Console.WriteLine("[7] backup");
                    Console.WriteLine("[8] requestbuild");
                    Console.WriteLine("[9] cleanbackup");
                    Console.WriteLine("[10] executeall");
                    subCommand = Console.ReadLine();
                    break;
                }
            }
        }
コード例 #25
0
        public async Task Logging_NoServiceProvider()
        {
            string testId = IdGenerator.FromDateTime();

            var builder = GetHostBuilder <VanillaApplication>(webHostBuilder =>
                                                              webHostBuilder.ConfigureLogging(loggingBuilder =>
            {
                var projectId = TestEnvironment.GetTestProjectId();
                var provider  = GoogleLoggerProvider.Create(serviceProvider: null, projectId, LoggerOptions.Create(LogLevel.Warning));
                loggingBuilder.AddProvider(provider);
            }));

            using (TestServer server = GetTestServer(builder))
                using (var client = server.CreateClient())
                {
                    await client.GetAsync($"/Main/Warning/{testId}");

                    await client.GetAsync($"/Main/Error/{testId}");

                    await client.GetAsync($"/Main/Critical/{testId}");
                }
            _fixture.AddValidator(testId, results =>
            {
                Assert.Equal(3, results.Count());
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Warning));
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Error));
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Critical));
            });
        }
コード例 #26
0
 public override void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) =>
 base.Configure(app, loggerFactory.AddGoogle(
                    app.ApplicationServices, _projectId, LoggerOptions.Create(logLevel: LogLevel.Warning, bufferOptions: BufferOptions.NoBuffer())));
コード例 #27
0
        private GoogleLogger GetLogger(IConsumer <LogEntry> consumer, LogLevel logLevel = LogLevel.Information)
        {
            LoggerOptions options = LoggerOptions.Create(logLevel);

            return(new GoogleLogger(consumer, s_logToProject, options, _logName, s_clock));
        }
コード例 #28
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
#pragma warning disable CS0618 // Type or member is obsolete - loggerFactory.AddConsole. We need to work out how to do all this better.
            if (StackdriverOptions.UseStackdriverLogging)
            {
                var platform      = Platform.Instance();
                var loggerOptions = LoggerOptions.Create(
                    logLevel: StackdriverOptions.LogLevel,
                    logName: StackdriverOptions.LogId ?? platform.GkeDetails?.ContainerName ?? "aspnetcore");
                loggerFactory.AddGoogle(app.ApplicationServices, platform.ProjectId, loggerOptions);
                if (StackdriverOptions.IncludeConsoleLogging)
                {
                    loggerFactory.AddConsole();
                }
            }
            else
            {
                // If we're not logging to Stackdriver, use console logging instead.
                loggerFactory.AddConsole();
                loggerFactory.AddDebug();
#pragma warning restore CS0618 // Type or member is obsolete
            }

            if (StackdriverOptions.UseStackdriverErrorReporting)
            {
                app.UseGoogleExceptionLogging();
            }

            app.UseForwardedHeaders();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            // Note: health checks come before HTTPS redirection so we get a 200 even on HTTP.
            app.UseHealthChecks("/healthz");
            app.UseHttpsRedirection();

            app.UseDefaultFiles();
            // Default content, e.g. CSS.
            // Even though we don't normally host the nzd files locally, it's useful to be able
            // to in case of emergency.
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider
                {
                    Mappings = { [".nzd"] = "application/octet-stream" }
                },
                OnPrepareResponse = context => SetCacheControlHeaderForStaticContent(env, context.Context)
            });

            // API documentation
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "docfx")),
                ContentTypeProvider = new FileExtensionContentTypeProvider
                {
                    Mappings = { [".yml"] = "text/x-yaml" }
                },
                OnPrepareResponse = context => SetCacheControlHeaderForStaticContent(env, context.Context)
            });
            // Captures "unstable" or a specific version - used several times below.
            string anyVersion     = @"((?:1\.[0-4]\.x)|(?:unstable)|(?:2\.[0-4]\.x))";
            var    rewriteOptions = new RewriteOptions()
                                    // Docfx wants index.html to exist, which is annoying... just redirect.
                                    .AddRedirect($@"^index.html$", "/")
                                    // We don't have an index.html or equivalent for the APIs, so let's go to NodaTime.html
                                    .AddRedirect($@"^{anyVersion}/api/?$", "$1/api/NodaTime.html")
                                    // Compatibility with old links
                                    .AddRedirect($@"^{anyVersion}/userguide/([^.]+)\.html$", "$1/userguide/$2")
                                    .AddRedirect($@"^developer/([^.]+)\.html$", "developer/$1")
                                    // Avoid links from userguide/unstable from going to userguide/core-concepts etc
                                    // (There are no doubt better ways of doing this...)
                                    .AddRedirect($@"^{anyVersion}/userguide$", "$1/userguide/")
                                    .AddRedirect($@"^developer$", "developer/")
                                    // Make /api and /userguide links to the latest stable release.
                                    .AddRedirect("^(api|userguide)(/.*)?$", "2.4.x/$1$2");
            app.UseRewriter(rewriteOptions);

            // At some stage we may want an MVC view for the home page, but at the moment
            // we're just serving static files, so we don't need much.
            app.UseMvc(routes =>
            {
                // TODO: Find a better way of routing. This is pretty nasty.
                routes.MapRoute("Developer docs", "developer/{*url}", new { controller = "Documentation", bundle = "developer", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("1.0.x user guide", "1.0.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.0.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("1.1.x user guide", "1.1.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.1.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("1.2.x user guide", "1.2.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.2.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("1.3.x user guide", "1.3.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.3.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("1.4.x user guide", "1.4.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.4.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("2.0.x user guide", "2.0.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.0.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("2.1.x user guide", "2.1.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.1.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("2.2.x user guide", "2.2.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.2.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("2.3.x user guide", "2.3.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.3.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("2.4.x user guide", "2.4.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.4.x", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("Unstable user guide", "unstable/userguide/{*url}", new { controller = "Documentation", bundle = "unstable", action = nameof(DocumentationController.ViewDocumentation) });
                routes.MapRoute("default", "{action=Index}/{id?}", new { controller = "Home" });
            });

            // Force all the Markdown to be loaded on startup.
            app.ApplicationServices.GetRequiredService <MarkdownLoader>();
            // Force the set of releases to be first loaded on startup.
            app.ApplicationServices.GetRequiredService <IReleaseRepository>().GetReleases();
            // Force the set of benchmarks to be first loaded on startup.
            app.ApplicationServices.GetRequiredService <IBenchmarkRepository>().ListEnvironments();
            // Force the set of TZDB data to be first loaded on startup.
            app.ApplicationServices.GetRequiredService <ITzdbRepository>().GetReleases();

#if BLAZOR
            app.Map("/blazor", child => child.UseBlazor <NodaTime.Web.Blazor.Program>());
#endif
        }
コード例 #29
0
        private static IHostBuilder GetUrlWriterHostBuilder()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLoggerWriteUrl_Core3
            var hostBuilder = Host.CreateDefaultBuilder()
                              .ConfigureWebHostDefaults(webBuilder => webBuilder
                                                        // Replace projectId with your Google Cloud Project ID.
                                                        .UseGoogleDiagnostics(projectId, loggerOptions: LoggerOptions.Create(loggerDiagnosticsOutput: Console.Out))
                                                        .UseStartup <Startup>());

            // End sample
            return(hostBuilder.ConfigureWebHost(webBuilder => webBuilder.UseTestServer()));
        }