private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, configurationBuilder) => { if (hostingContext.HostingEnvironment.ApplicationName.IsNullOrWhitespace()) { hostingContext.HostingEnvironment.ApplicationName = Assembly.GetEntryAssembly()?.GetName().Name; } var localConfigFile = HostBuilderExtensions.CloneLocalConfiguration(hostingContext.HostingEnvironment.ApplicationName); configurationBuilder .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", true, true); configurationBuilder.AddJsonFile( hostingContext.HostingEnvironment.IsDevelopment() ? $"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json" : localConfigFile, true, true); configurationBuilder.AddEnvironmentVariables(); }) .UseSerilog((hostingContext, loggerConfiguration) => { loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.FromLogContext() .WriteTo.ColoredConsole(outputTemplate: "[{Timestamp:HH:mm:ss:fff} {Level:u3}] {SourceContext:l} {Message:lj}{NewLine}{Exception}"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); });
public void UseCloudHosting_Web_ThrowsIfHostBuilderNull() { IWebHostBuilder webHostBuilder = null; var ex = Assert.Throws <ArgumentNullException>(() => HostBuilderExtensions.UseCloudHosting(webHostBuilder)); Assert.Contains(nameof(webHostBuilder), ex.Message); }
public TransactionNameTests(WebApplicationFactory <Startup> factory) { _factory = factory; _agent = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender, // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer)); HostBuilderExtensions.UpdateServiceInformation(_agent.Service); }
public void UseConductorly_BindsExpectedImplementations() { var mockServiceCollection = new Mock <IServiceCollection>(); var hostBuilder = new TestHostBuilder(mockServiceCollection.Object); HostBuilderExtensions.UseConductorly(hostBuilder); mockServiceCollection.Verify(mock => mock.Add( It.Is <ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IConductorly) && descriptor.ImplementationType == typeof(Conductorly.Conductorly) && descriptor.Lifetime == ServiceLifetime.Singleton)), Times.Once); }
private static void StartAgent() { Agent.Setup(new AgentComponents()); var logger = StartupHookLogger.Create(); LoadDiagnosticSubscriber(new HttpDiagnosticsSubscriber(), logger); LoadDiagnosticSubscriber(new AspNetCoreDiagnosticSubscriber(), logger); LoadDiagnosticSubscriber(new EfCoreDiagnosticsSubscriber(), logger); LoadDiagnosticSubscriber(new SqlClientDiagnosticSubscriber(), logger); LoadDiagnosticSubscriber(new ElasticsearchDiagnosticsSubscriber(), logger); LoadDiagnosticSubscriber(new GrpcClientDiagnosticSubscriber(), logger); HostBuilderExtensions.UpdateServiceInformation(Agent.Instance.Service);
public static async Task Main(string[] args) { ISharedConfiguration SharedConfiguration = HostBuilderExtensions.CreateConfigurationBuilder().Configuration(); IHostBuilder builder = CreateHostBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseConfiguration(SharedConfiguration) .UseStartup <Startup>() .CompleteHostConfiguration(SharedConfiguration); }); await builder.Build().RunAsync(); }
public AspNetCoreBasicTests(WebApplicationFactory <Startup> factory, ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { _logger = LoggerBase.Scoped(nameof(AspNetCoreBasicTests)); _factory = factory; _agent = new ApmAgent(new TestAgentComponents( _logger, new MockConfigSnapshot(_logger, captureBody: ConfigConsts.SupportedValues.CaptureBodyAll), // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer) ); HostBuilderExtensions.UpdateServiceInformation(_agent.Service); _capturedPayload = _agent.PayloadSender as MockPayloadSender; }
public TransactionIgnoreUrlsTest(WebApplicationFactory <Startup> factory) { _factory = factory; _logger = new NoopLogger(); // _logger.Scoped(ThisClassName); _agent = new ApmAgent(new TestAgentComponents( _logger, new MockConfigSnapshot(_logger, transactionIgnoreUrls: "*simplepage"), // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer) ); HostBuilderExtensions.UpdateServiceInformation(_agent.Service); _capturedPayload = _agent.PayloadSender as MockPayloadSender; }
public TransactionNameTests(WebApplicationFactory <Startup> factory, ITestOutputHelper testOutputHelper) { _factory = factory; var logger = new LineWriterToLoggerAdaptor(new XunitOutputToLineWriterAdaptor(testOutputHelper)) { LogLevelSwitch = { Level = LogLevel.Trace } }; _agent = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender, logger: logger, // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer)); HostBuilderExtensions.UpdateServiceInformation(_agent.Service); }
public void Setup() { var services = new ServiceCollection(); HostBuilderExtensions.CreateConfigurationBuilder(services); services.AddTrace(); options = services.GetDbContextOptions(); services.AddAutoMapper(typeof(Fs.Business.Mappings.MappingProfile).Assembly); IServiceProvider serviceProvider = services.BuildServiceProvider(); services.RegisterAppServices(); logger = serviceProvider.GetRequiredService <ILogger <OrderService> >(); mapper = serviceProvider.GetRequiredService <IMapper>(); Fs.Core.Trace.Write("Setup()", "Completed", System.Diagnostics.TraceLevel.Info); }
/// <summary> /// Adds the Elastic APM Middleware to the ASP.NET Core pipeline. /// You can customize the agent by passing additional IDiagnosticsSubscriber components to this method. /// Use this method if you want to control what tracing capability of the agent you would like to use /// or in case you want to minimize the number of dependencies added to your application. /// Please note that by default without additional parameters this method only enables ASP.NET Core /// monitoring - e.g. database statements or outgoing HTTP calls won't be traced. /// If you want to simply enable every tracing component without configuration please use the /// UseAllElasticApm extension method from the Elastic.Apm.NetCoreAll package. /// </summary> /// <returns>The elastic apm.</returns> /// <param name="builder">Builder.</param> /// <param name="configuration"> /// You can optionally pass the IConfiguration of your application to the Elastic APM Agent. By /// doing this the agent will read agent related configurations through this IConfiguration instance. /// If no <see cref="IConfiguration" /> is passed to the agent then it will read configs from environment variables. /// </param> /// <param name="subscribers"> /// Specify which diagnostic source subscribers you want to connect. The /// <see cref="AspNetCoreDiagnosticsSubscriber" /> is by default enabled. /// </param> public static IApplicationBuilder UseElasticApm( this IApplicationBuilder builder, IConfiguration configuration = null, params IDiagnosticsSubscriber[] subscribers ) { var logger = builder.ApplicationServices.GetApmLogger(); var configReader = configuration == null ? new EnvironmentConfigurationReader(logger) : new MicrosoftExtensionsConfig(configuration, logger, builder.ApplicationServices.GetEnvironmentName()) as IConfigurationReader; var config = new AgentComponents(configurationReader: configReader, logger: logger); HostBuilderExtensions.UpdateServiceInformation(config.Service); Agent.Setup(config); return(UseElasticApm(builder, Agent.Instance, logger, subscribers)); }
public TransactionIgnoreUrlsTest(WebApplicationFactory <Startup> factory, ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { _factory = factory; _logger = LoggerBase.Scoped(ThisClassName); _agent = new ApmAgent(new TestAgentComponents( _logger, new MockConfigSnapshot(_logger, transactionIgnoreUrls: "*simplepage"), // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer) ); HostBuilderExtensions.UpdateServiceInformation(_agent.Service); _capturedPayload = _agent.PayloadSender as MockPayloadSender; _client = Helper.GetClient(_agent, _factory); #if NETCOREAPP3_0 || NETCOREAPP3_1 _client.DefaultRequestVersion = new Version(2, 0); #endif }
/// <summary> /// Adds the Elastic APM Middleware to the ASP.NET Core pipeline. /// You can customize the agent by passing additional IDiagnosticsSubscriber components to this method. /// Use this method if you want to control what tracing capability of the agent you would like to use /// or in case you want to minimize the number of dependencies added to your application. /// Please note that by default without additional parameters this method only enables ASP.NET Core /// monitoring - e.g. database statements or outgoing HTTP calls won't be traced. /// If you want to simply enable every tracing component without configuration please use the /// UseAllElasticApm extension method from the Elastic.Apm.NetCoreAll package. /// </summary> /// <returns>The elastic apm.</returns> /// <param name="builder">Builder.</param> /// <param name="configuration"> /// You can optionally pass the IConfiguration of your application to the Elastic APM Agent. By /// doing this the agent will read agent related configurations through this IConfiguration instance. /// If no <see cref="IConfiguration" /> is passed to the agent then it will read configs from environment variables. /// </param> /// <param name="subscribers"> /// Specify which diagnostic source subscribers you want to connect. The /// <see cref="AspNetCoreErrorDiagnosticsSubscriber" /> is by default enabled. /// </param> public static IApplicationBuilder UseElasticApm( this IApplicationBuilder builder, IConfiguration configuration = null, params IDiagnosticsSubscriber[] subscribers ) { var logger = builder.ApplicationServices.GetApmLogger(); var configReader = configuration == null ? new EnvironmentConfigurationReader(logger) : new MicrosoftExtensionsConfig(configuration, logger, builder.ApplicationServices.GetEnvironmentName()) as IConfigurationReader; var config = new AgentComponents(configurationReader: configReader, logger: logger); HostBuilderExtensions.UpdateServiceInformation(config.Service); // Agent.Setup must be called, even if agent is disabled. This way static public API usage won't implicitly initialize an agent with default values, instead, this will be reused. Agent.Setup(config); return(UseElasticApm(builder, Agent.Instance, logger, subscribers)); }
public void ConfigureExternalConfiguration_HostBuilderIsNull_ThrowsArgumentNullException() { var exception = Assert.Throws <ArgumentNullException>(() => HostBuilderExtensions.ConfigureExternalConfiguration(null)); Assert.Equal("builder", exception.ParamName); }
public static IHostBuilder CreateHostBuilder(string[] args) => HostBuilderExtensions.CreateDefaultWebApiHostBuilder <Startup>(args);
public static async Task Main(string[] args) { var coolStoreWebHostBuilder = HostBuilderExtensions.CreateCoolStoreWebHostBuilder(typeof(Startup)); var host = coolStoreWebHostBuilder.Build(); await host.RunAsync(); }
public void UseHostedService_configure_services([Frozen] IServiceCollection services, IHostBuilder builder) { HostBuilderExtensions.UseHostedService <NybusHostedService>(builder); Mock.Get(builder).Verify(p => p.ConfigureServices(It.IsAny <Action <HostBuilderContext, IServiceCollection> >())); }
public void UseHostedService_requires_hostBuilder() { Assert.Throws <ArgumentNullException>(() => HostBuilderExtensions.UseHostedService <NybusHostedService>(null)); }
public StreamsHostBuilder(IHostBuilder hostBuilder) { _hostBuilder = hostBuilder.ConfigureServices(HostBuilderExtensions.ConfigureStreamsDelegate <T>()); }
public void UseApplicationMetadata_HostBuilderIsNull_ThrowsArgumentNullException() { var exception = Assert.Throws <ArgumentNullException>(() => HostBuilderExtensions.UseApplicationMetadata(null)); Assert.Equal("builder", exception.ParamName); }