/// <summary> /// Adds a default test logger that collect logs. /// </summary> /// <param name="builder">The <see cref="IWebHostBuilder"/> to add the test logger to.</param> /// <returns>A reference to the <paramref name="builder"/> after the operation has completed.</returns> public static IWebHostBuilder UseTestLogging(this IWebHostBuilder builder) => builder.ConfigureLogging(logging => logging.AddTest());
/// <summary> /// Adds a configured test logger that collect logs. /// </summary> /// <param name="builder">The <see cref="IWebHostBuilder"/> to add the test logger to.</param> /// <param name="configure">A delegate used to configure the <see cref="TestLoggerOptions"/>.</param> /// <returns>A reference to the <paramref name="builder"/> after the operation has completed.</returns> public static IWebHostBuilder UseTestLogging(this IWebHostBuilder builder, Action <TestLoggerOptions> configure) => builder.ConfigureLogging(logging => logging.AddTest(configure));
public static IWebHostBuilder WithNoOutput(this IWebHostBuilder builder) { return(builder.ConfigureLogging((ILoggingBuilder logBuilder) => { logBuilder.ClearProviders(); })); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseWebRoot(Path.GetFullPath("wwwroot")); builder.ConfigureAppConfiguration((context, b) => { b.SetBasePath(Path.GetFullPath("wwwroot")) .AddJsonFile("config.json", false, true); b.AddInMemoryCollection(new Dictionary <string, string> { { "AppSettings:SitecoreIdentityServerUrl", "http://localhost" }, { "Logging:LogLevel:Default", "Debug" }, { "Logging:PipelineTraceLoggingEnabled", "true" } }); }); base.ConfigureWebHost(builder); builder.UseSolutionRelativeContentRoot("") .UseStartup <Startup>(); builder.ConfigureLogging(c => { c.AddProvider(new XunitLoggerProvider(getTestOutputHelper())); }); builder.ConfigureServices(c => { c.Configure <IdentityServerAuthenticationOptions>("Bearer", options => { options.Authority = "http://localhost"; // This makes sure the commerce engine contacts the in memory identity server options.JwtBackChannelHandler = identityServerHandler; options.IntrospectionDiscoveryHandler = identityServerHandler; options.IntrospectionBackChannelHandler = identityServerHandler; }); }); builder.ConfigureTestServices(services => { services.AddTransient <GetDatabaseVersionCommand, DummyGetDatabaseVersionCommand>(); /************************************** Persistent ***********************************/ services.AddSingleton <IStore>(inMemoryStore); services.AddSingleton(inMemoryStore); services.AddSingleton <IListStore>(inMemoryListStore); services.AddSingleton(inMemoryListStore); Assembly assembly = Assembly.GetExecutingAssembly(); services.RegisterAllPipelineBlocks(assembly); services.Sitecore().Pipelines(config => config.ConfigurePipeline <IFindEntitiesInListPipeline>(c => { c.Clear(); c.Add <FindEntitiesInListBlock>(); }) .ConfigurePipeline <IFindEntityPipeline>(c => { c.Clear(); c.Add <FindEntityBlock>(); })); }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseSolutionRelativeContentRoot(@"src\HttpContextBackground"); builder.ConfigureLogging(logBuilder => logBuilder.ClearProviders()); }
/// <inheritdoc /> protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureLogging((p) => p.AddXUnit(this)); }
/// <inheritdoc /> protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureLogging((loggingBuilder) => loggingBuilder.ClearProviders().AddXUnit());
public IWebHostBuilder ConfigureLogging(Action <ILoggerFactory> configureLogging) { _builder.ConfigureLogging(configureLogging); return(this); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureLogging(logging => logging.AddTestLogger(Sink)); }
/// <summary> /// Sets XLogger as the logging provider. /// </summary> /// <param name="builder">The web host builder to configure.</param> /// <param name="loggerHubOptions">The logger hub options and preferences.</param> /// <returns>The web host builder.</returns> public static IWebHostBuilder UseXLogger(this IWebHostBuilder builder, Action <ILoggerHub> loggerHubOptions) => builder.ConfigureLogging((hostingContext, logging) => logging.RegisterLoggerHub(loggerHubOptions));
public static IWebHostBuilder AddCloudFoundryActuators(this IWebHostBuilder webHostBuilder, MediaTypeVersion mediaTypeVersion, Action <CorsPolicyBuilder> buildCorsPolicy = null) => webHostBuilder .ConfigureLogging((context, configureLogging) => configureLogging.AddDynamicConsole()) .ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration, mediaTypeVersion, buildCorsPolicy));
/// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .ConfigureLogging(config => config.ClearProviders().AddProvider(new LogProvider(new JsonLogger())).AddFilter("Microsoft", LogProvider.Filter)) .UseStartup <Startup>(); }
/// <summary> /// Adds all Actuators supported by Apps Manager. Also configures DynamicLogging if not previously setup. /// </summary> /// <param name="webHostBuilder">Your Hostbuilder</param> /// <param name="mediaTypeVersion">Spring Boot media type version to use with responses</param> /// <param name="actuatorContext">Select how targeted to Apps Manager actuators should be</param> /// <param name="buildCorsPolicy">Customize the CORS policy. </param> public static IWebHostBuilder AddCloudFoundryActuators(this IWebHostBuilder webHostBuilder, MediaTypeVersion mediaTypeVersion, ActuatorContext actuatorContext, Action <CorsPolicyBuilder> buildCorsPolicy = null) { return(webHostBuilder .ConfigureLogging(ConfigureDynamicLogging) .ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration, mediaTypeVersion, actuatorContext, buildCorsPolicy))); }
public static IWebHostBuilder UseTestLogging(this IWebHostBuilder builder, ITestSink sink) => builder.ConfigureLogging(logging => logging.AddTestLogger(sink));
protected override TestServer CreateServer(IWebHostBuilder builder) { builder.ConfigureLogging((p) => p.AddXUnit()); return(base.CreateServer(builder)); }
public StressServer(Configuration configuration) { ServerUri = configuration.ServerUri; IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (configuration.UseHttpSys) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { hso.UrlPrefixes.Add(ServerUri.ToString()); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { // conservative estimation based on https://github.com/aspnet/AspNetCore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); IPAddress iPAddress = Dns.GetHostAddresses(configuration.ServerUri.Host).First(); ko.Listen(iPAddress, configuration.ServerUri.Port, listenOptions => { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest($"CN={ServerUri.Host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } }); }); }; // Output only warnings and errors from Kestrel host = host .ConfigureLogging(log => log.AddFilter("Microsoft.AspNetCore", level => configuration.LogAspNet ? level >= LogLevel.Warning : false)) // Set up how each request should be handled by the server. .Configure(app => { var head = new[] { "HEAD" }; app.UseRouting(); app.UseEndpoints(e => MapRoutes(e, configuration.MaxContentLength)); }); // Handle command-line arguments. _eventListener = configuration.LogPath == null ? null : new HttpEventListener(configuration.LogPath != "console" ? new StreamWriter(configuration.LogPath) { AutoFlush = true } : null); SetUpJustInTimeLogging(); _webHost = host.Build(); _webHost.Start(); }
public static IWebHostBuilder UseNLogExtension(this IWebHostBuilder builder) => builder.ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog();
/// <summary> /// Run the application /// </summary> /// <param name="cancelToken">Cancel token</param> /// <returns>Task</returns> public async virtual Task StartAsync(CancellationToken cancelToken) { IWebHostBuilder builder = WebHost.CreateDefaultBuilder(Args); builder.ConfigureLogging(logging => { #if !DEBUG logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning); #endif }); Dictionary <string, string> argsDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (Args.Length % 2 != 0) { throw new ArgumentException("Arg count must be even. Use a space in between parameter names and values"); } for (int i = 0; i < Args.Length;) { argsDictionary[Args[i++]] = Args[i++].Trim(); } builder.UseKestrel(c => c.AddServerHeader = false); builder.UseIISIntegration(); builder.UseContentRoot(RootDirectory); builder.UseConfiguration(Configuration); argsDictionary.TryGetValue("--server.urls", out string serverUrl); IConfigurationSection web = Configuration.GetSection("mailDemonWeb"); Authority = web["authority"]; string certPathWeb = web["sslCertificateFile"]; string certPathPrivateWeb = web["sslCertificatePrivateKeyFile"]; SecureString certPasswordWeb = web["sslCertificatePassword"]?.ToSecureString(); if (File.Exists(certPathWeb) && File.Exists(certPathPrivateWeb)) { builder.ConfigureKestrel((opt) => { opt.Listen((serverUrl == null ? System.Net.IPAddress.Any : System.Net.IPAddress.Parse(serverUrl)), 443, listenOptions => { listenOptions.UseHttps((sslOpt) => { sslOpt.ServerCertificateSelector = (ctx, name) => { return(CertificateCache.Instance.LoadSslCertificateAsync(certPathWeb, certPathPrivateWeb, certPasswordWeb).Sync()); }; }); }); }); } else if (serverUrl != null) { builder.UseUrls(serverUrl.Split(',', '|', ';')); } try { host = builder.ConfigureServices(services => { services.AddSingleton <IStartup>(this); }).Build(); } catch (Exception ex) { MailDemonLog.Error(ex); } Recaptcha = new RecaptchaSettings(web["recaptchaSiteKey"], web["recaptchaSecretKey"]); AdminLogin = new KeyValuePair <string, string>(web["adminUser"], web["adminPassword"]); Task runTask = host.RunAsync(CancelToken); // do not return the task until we know we are running, for tests for example, we don't want requests coming // in until everything is setup and listening properly if (!runningEvent.WaitOne(10000)) // if 10 seconds and not running, fail { throw new ApplicationException("Failed to start app " + GetType().Name); } await runTask; }
public void Configure(IWebHostBuilder builder) { builder.ConfigureLogging((context, logging) => logging.AddProvider(new FooLoggerProvider())); }