public static void Main() { var appDir = AssemblyDirectory; var configurationBuilder = new ConfigurationBuilder() .SetBasePath(appDir) .AddJsonFile("appsettings.json"); var configuration = configurationBuilder.Build(); string SettingsResolver(string name) => configuration[name]; var apiUrl = SettingsResolver("ApiUrl"); MongoDbConfiguration.ServerAddress = SettingsResolver("MongoDB.ServerAddress"); MongoDbConfiguration.ServerPort = int.Parse(SettingsResolver("MongoDB.ServerPort")); MongoDbConfiguration.DatabaseName = SettingsResolver("MongoDB.DatabaseName"); MongoDbConfiguration.UserName = SettingsResolver("MongoDB.UserName"); MongoDbConfiguration.UserPassword = SettingsResolver("MongoDB.UserPassword"); using (DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { var host = new WebHostBuilder() .UseUrls(apiUrl) .UseKestrel() .UseContentRoot(appDir) .UseStartup <Startup>() .Build(); TraceInformation($"WebAPI starting at {apiUrl}"); TraceInformation($"Using MongoDB at {MongoDbConfiguration.ServerAddress}:{MongoDbConfiguration.ServerPort}/{MongoDbConfiguration.DatabaseName}"); host.Run(); } }
public void AddsMetadataToMetricTelemetry() { UnitTestOutput unitTestOutput = null; DateTimeOffset now = DateTimeOffset.Now; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(diagnosticPipelineConfiguration_.Value)) { unitTestOutput = pipeline.Sinks.First().Output as UnitTestOutput; TelemetryConfiguration telemetryConfiguration = GetAppInsightsTestTelemetryConfiguration(); EventFlowTelemetryProcessor efTelemetryProcessor = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors.OfType <EventFlowTelemetryProcessor>().First(); efTelemetryProcessor.Pipeline = pipeline; TelemetryClient client = new TelemetryClient(telemetryConfiguration); MetricTelemetry metric = new MetricTelemetry("rps", 223.7d); metric.Timestamp = now; client.TrackMetric(metric); } Assert.Equal(1, unitTestOutput.EventCount); Assert.True(unitTestOutput.CapturedEvents.TryDequeue(out EventData eventData)); Assert.Equal(now, eventData.Timestamp); Assert.True(eventData.TryGetMetadata(MetricData.MetricMetadataKind, out IReadOnlyCollection <EventMetadata> eventMetadata)); Assert.Equal(1, eventMetadata.Count); EventMetadata metricMetadata = eventMetadata.ElementAt(0); Assert.Equal(DataRetrievalResult.Success, MetricData.TryGetData(eventData, metricMetadata, out MetricData metricData)); Assert.Equal("rps", metricData.MetricName); Assert.Equal(223.7d, metricData.Value); }
public void AddsMetadataToRequestTelemetry() { UnitTestOutput unitTestOutput = null; DateTimeOffset now = DateTimeOffset.Now; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(diagnosticPipelineConfiguration_.Value)) { unitTestOutput = pipeline.Sinks.First().Output as UnitTestOutput; TelemetryConfiguration telemetryConfiguration = GetAppInsightsTestTelemetryConfiguration(); EventFlowTelemetryProcessor efTelemetryProcessor = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors.OfType <EventFlowTelemetryProcessor>().First(); efTelemetryProcessor.Pipeline = pipeline; TelemetryClient client = new TelemetryClient(telemetryConfiguration); client.TrackRequest("rqName", now, TimeSpan.FromMilliseconds(123), "418 I am a teapot", false); } Assert.Equal(1, unitTestOutput.EventCount); Assert.True(unitTestOutput.CapturedEvents.TryDequeue(out EventData eventData)); Assert.Equal(now, eventData.Timestamp); Assert.True(eventData.TryGetMetadata(RequestData.RequestMetadataKind, out IReadOnlyCollection <EventMetadata> eventMetadata)); Assert.Equal(1, eventMetadata.Count); EventMetadata requestMetadata = eventMetadata.ElementAt(0); Assert.Equal(DataRetrievalResult.Success, RequestData.TryGetData(eventData, requestMetadata, out RequestData requestData)); Assert.Equal("rqName", requestData.RequestName); Assert.False(requestData.IsSuccess); Assert.Equal(TimeSpan.FromMilliseconds(123), requestData.Duration); Assert.Equal("418 I am a teapot", requestData.ResponseCode); }
static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { Instrumentation.Log.Started(); // Give other eventsources a chance to load and be enabled Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith( _ => { Log.Trace().Message("Trace").Write(); Log.Debug().Message("Debug").Write(); Log.Info().Message("Info").Write(); Log.Warn().Message("Warn").Write(); Log.Error().Message("Error").Write(); Log.Fatal().Message("Fatal").Write(); } ); Console.WriteLine("Hit <Return> to exit"); Console.ReadLine(); Instrumentation.Log.Stopped(); } }
public void AddsMetadataDependencyTelemetry() { UnitTestOutput unitTestOutput = null; DateTimeOffset now = DateTimeOffset.Now; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(diagnosticPipelineConfiguration_.Value)) { unitTestOutput = pipeline.Sinks.First().Output as UnitTestOutput; TelemetryConfiguration telemetryConfiguration = GetAppInsightsTestTelemetryConfiguration(); EventFlowTelemetryProcessor efTelemetryProcessor = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors.OfType <EventFlowTelemetryProcessor>().First(); efTelemetryProcessor.Pipeline = pipeline; TelemetryClient client = new TelemetryClient(telemetryConfiguration); client.TrackDependency("FlawlessDependency", "https://flawless.microsoft.com", "dpName", "payload", now, TimeSpan.FromMilliseconds(178), "201 Created", success: true); } Assert.Equal(1, unitTestOutput.EventCount); Assert.True(unitTestOutput.CapturedEvents.TryDequeue(out EventData eventData)); Assert.Equal(now, eventData.Timestamp); Assert.True(eventData.TryGetMetadata(DependencyData.DependencyMetadataKind, out IReadOnlyCollection <EventMetadata> eventMetadata)); Assert.Equal(1, eventMetadata.Count); EventMetadata dependencyMetadata = eventMetadata.ElementAt(0); Assert.Equal(DataRetrievalResult.Success, DependencyData.TryGetData(eventData, dependencyMetadata, out DependencyData dependencyData)); Assert.True(dependencyData.IsSuccess); Assert.Equal(TimeSpan.FromMilliseconds(178), dependencyData.Duration); Assert.Equal("201 Created", dependencyData.ResponseCode); Assert.Equal("https://flawless.microsoft.com", dependencyData.Target); Assert.Equal("FlawlessDependency", dependencyData.DependencyType); }
static async Task Main() { var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"); var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(XDocument.Load("serilog.xml").Root.Elements().ToDictionary(x => x.Attribute("Name").Value, x => x.Attribute("Value").Value)); var logger = CreateLogger(pipeline, builder.Build()); LogManager .Use <SerilogFactory>() .WithLogger(logger); Console.Title = "Samples.Logging.Default"; #region ConfigureLogging var endpointConfiguration = new EndpointConfiguration("Samples.Logging.Default"); // No config is required in version 5 and // higher since logging is enabled by default #endregion endpointConfiguration.UsePersistence <LearningPersistence>(); endpointConfiguration.UseTransport <LearningTransport>(); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); var myMessage = new MyMessage(); await endpointInstance.SendLocal(myMessage) .ConfigureAwait(false); Console.WriteLine("Press any key to exit"); Console.ReadKey(); await endpointInstance.Stop() .ConfigureAwait(false); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("PlayGround.exe <projectId> <datasetId>"); return; } var projectId = args[0]; var datasetId = args[1]; var eventFlowConfigJson = File.ReadAllText("eventFlowConfig.json"); eventFlowConfigJson = eventFlowConfigJson .Replace("<projectId>", projectId) .Replace("<datasetId>", datasetId); var fileProvider = new StringFileProvider(eventFlowConfigJson); var config = new ConfigurationBuilder().AddJsonFile(fileProvider, "eventFlowConfig.json", false, false).Build(); using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(config)) { PlayWithTrace(pipeline); PlayWithEventSource(pipeline); PlayWithMicrosoftLogging(pipeline); Console.WriteLine("Press any key to exit..."); Console.ReadKey(intercept: true); } }
public static DiagnosticPipeline CreatePipeline(string healthEntityName, string configurationFileName = "eventFlowConfig.json") { // TODO: dynamically re-configure the pipeline when configuration changes, without stopping the service Requires.NotNullOrWhiteSpace(healthEntityName, nameof(healthEntityName)); var healthReporter = new ServiceFabricHealthReporter(healthEntityName); CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext(); ConfigurationPackage configPackage = activationContext.GetConfigurationPackageObject("Config"); string configFilePath = Path.Combine(configPackage.Path, configurationFileName); if (!File.Exists(configFilePath)) { string errorMessage = $"{nameof(ServiceFabricDiagnosticPipelineFactory)}: configuration file '{configFilePath}' is missing or inaccessible"; healthReporter.ReportProblem(errorMessage, EventFlowContextIdentifiers.Configuration); throw new Exception(errorMessage); } ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile(configFilePath); IConfigurationRoot configurationRoot = configBuilder.Build(); return(DiagnosticPipelineFactory.CreatePipeline(configurationRoot, new ServiceFabricHealthReporter(healthEntityName))); }
public static void Monitor(CancellationToken cancellationToken) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { System.Diagnostics.Trace.TraceWarning("EventFlow is working!"); Task.Delay(Timeout.Infinite, cancellationToken).GetAwaiter().GetResult(); } }
public static async Task Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { await CreateHostBuilder(args, pipeline) .Build() .RunAsync(); } }
static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { System.Diagnostics.Trace.TraceInformation("EventFlow is working!"); Console.WriteLine("Collecting events. Press any key to exit..."); Console.ReadKey(intercept: true); } }
static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { PlayWithTrace(pipeline); Console.WriteLine("Press any key to exit..."); Console.ReadKey(intercept: true); } }
static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { // In this example, Trace is assumed as one of the Input sources. System.Diagnostics.Trace.TraceInformation("EventFlow is working - Information!"); System.Diagnostics.Trace.TraceWarning("EventFlow is working - Warning!"); System.Diagnostics.Trace.TraceError("EventFlow is working - Error!"); // Console.ReadLine(); } }
public void Run() { IWebHost webHost = CreateWebHostBuilder().Build(); IConfiguration configuration = webHost.Services.GetRequiredService <IConfiguration>(); IConfiguration eventFlowConfig = configuration.GetSection("EventFlowConfig"); using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(eventFlowConfig)) { ILoggerFactory loggerFactory = webHost.Services.GetRequiredService <ILoggerFactory>(); loggerFactory.AddEventFlow(pipeline); webHost.Run(); } }
public static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("config.json")) { for (int i = 0; i < 200000; i++) { // You shall not need to call this unless you really want to diagnose EventHub issue. pipeline.HealthReporter.ReportHealthy("Some health report content. . ."); Thread.Sleep(1); } Trace.TraceWarning("EventFlow is working!"); Console.ReadLine(); } }
private void RegisterLog() { var pipe = DiagnosticPipelineFactory.CreatePipeline("eventFlow.json"); _loggerFactory = new LoggerFactory().AddEventFlow(pipe); var loggerService = new LoggerService(new Log <LoggerService>(_loggerFactory)); _factory.Register <ILoggerService>( loggerService ); _factory.Register <IResponseUtil>( new ResponseUtil(loggerService) ); }
public void ShouldUse3rdPartyHealthReporterIfSpecified() { string pipelineConfiguration = @" { ""inputs"": [ { ""type"": ""EventSource"", ""sources"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, ] } ], ""outputs"": [ { ""type"": ""StdOutput"", } ], ""schemaVersion"": ""2016-08-11"", ""extensions"": [ { ""category"": ""healthReporter"", ""type"": ""CustomHealthReporter"", ""qualifiedTypeName"": ""Microsoft.Diagnostics.EventFlow.Core.Tests.CustomHealthReporter, Microsoft.Diagnostics.EventFlow.Core.Tests"" } ], ""healthReporter"": { ""type"": ""CustomHealthReporter"", } }"; using (var configFile = new TemporaryFile()) { configFile.Write(pipelineConfiguration); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile(configFile.FilePath); var configuration = builder.Build(); var mocked = new Mock <IHealthReporter>(); var isHP = mocked is IHealthReporter; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(configuration)) { Assert.NotNull(pipeline); Assert.True(pipeline.HealthReporter is CustomHealthReporter); } } }
public static void Run([TimerTrigger("00:00:03")] TimerInfo myTimer, TraceWriter log) { string folder = @"C:\Rot\EventFlowFunctionApp1\EventFlowFunctionApp1\bin\Debug\net47\"; using (var diagnosticsPipeline = DiagnosticPipelineFactory.CreatePipeline(Path.Combine(folder, "eventFlowConfig.json"))) { // Configure logging var loggerFactory = new LoggerFactory() .AddEventFlow(diagnosticsPipeline); IServiceProvider serviceProvider = new ServiceCollection() .AddSingleton <ILoggerFactory>(loggerFactory) .BuildServiceProvider(); ILogger logger = loggerFactory.CreateLogger(typeof(Function1)); logger.LogInformation("Some log item"); log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); } }
private void InitializePipeline() { TelemetryConfiguration.Active.TelemetryInitializers .Add(new MyTelemetryInitializer()); var configuration = new ConfigurationBuilder() .AddJsonFile("eventFlowConfig.json", optional: true, reloadOnChange: true) .Build(); var environmentKey = CatalogConfiguration.AppInsightsInstrumentationKey; if (!string.IsNullOrEmpty(environmentKey)) { configuration["outputs:0:instrumentationKey"] = environmentKey; TelemetryConfiguration.Active.InstrumentationKey = environmentKey; } diagnosticsPipeline = DiagnosticPipelineFactory.CreatePipeline(configuration); }
static void Main(string[] args) { using (DiagnosticPipeline pipeline = DiagnosticPipelineFactory.CreatePipeline(".\\eventFlowConfig.json")) { var logger = LogManager.GetLogger("EventFlowRepo", "MY_LOGGER_NAME"); #region log4net without context params logger.Debug("Hey! Listen!", new Exception("uhoh")); #endregion Console.ReadKey(true); #region log4net input with stacks and global context GlobalContext.Properties["GlobalContext"] = "My Global Context"; using (ThreadContext.Stacks["NDC"].Push("Thread Context-1")) { using (ThreadContext.Stacks["NDC"].Push("Thread Context-1-1")) { using (LogicalThreadContext.Stacks["LogicalThreadContext"].Push("Logical Thread Context-1-1-1")) { logger.Debug("Hey! Listen!", new Exception("uhoh")); } logger.Info("From Thread Context 1-1"); } logger.Info("From Thread Context 1"); } #endregion Console.ReadLine(); // Build up the pipeline Console.WriteLine("Pipeline is created."); // Send a trace to the pipeline Trace.TraceInformation("This is a message from trace . . ."); MyEventSource.Log.Message("This is a message from EventSource ..."); // Make a simple get request to bing.com just to generate some HTTP trace HttpClient client = new HttpClient(); client.GetStringAsync("http://www.bing.com").Wait(); // Check the result Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(true); } }
public void ReportsAllTelemetryTypes() { UnitTestOutput unitTestOutput = null; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(diagnosticPipelineConfiguration_.Value)) { unitTestOutput = pipeline.Sinks.First().Output as UnitTestOutput; TelemetryConfiguration telemetryConfiguration = GetAppInsightsTestTelemetryConfiguration(); EventFlowTelemetryProcessor efTelemetryProcessor = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors.OfType <EventFlowTelemetryProcessor>().First(); efTelemetryProcessor.Pipeline = pipeline; TelemetryClient client = new TelemetryClient(telemetryConfiguration); client.TrackTrace("This is a trace"); client.TrackRequest("DoStuff", DateTimeOffset.UtcNow, TimeSpan.FromMilliseconds(20), "200 OK", success: true); client.TrackEvent("ImportantEvent", new Dictionary <string, string> { { "eventProp", "foo" } }); client.TrackDependency("otherService", "inquire", DateTimeOffset.UtcNow, TimeSpan.FromMilliseconds(57), success: true); client.TrackMetric("rps", 340.7); try { throw new Exception("Oops!"); } catch (Exception e) { client.TrackException(e); } client.TrackPageView("Home page"); client.TrackAvailability("frontend-service-ping", DateTimeOffset.UtcNow, TimeSpan.FromMilliseconds(73.5), "Munich-DE", success: true); } Assert.Equal(8, unitTestOutput.EventCount); Assert.Collection(unitTestOutput.CapturedEvents, e => Assert.Equal("trace", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("request", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("event", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("dependency", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("metric", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("exception", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("page_view", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty]), e => Assert.Equal("availability", e.Payload[EventFlowTelemetryProcessor.TelemetryTypeProperty])); }
static void Main(string[] args) { TelemetryConfiguration.Active.TelemetryInitializers.Add(new CorrelationTelemetryInitializer()); TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; using (DiagnosticPipeline pipeline = DiagnosticPipelineFactory.CreatePipeline("config.json")) { for (int i = 0; i < 10; i++) { ContextResolver.SetRequestContext(new MyContext { CorrelationId = Guid.NewGuid().ToString(), OtherId = i.ToString() }); Trace.TraceWarning($"{DateTime.UtcNow:o} this is log message"); } Task.Delay(10000).Wait(); } }
private static void Main() { using (DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(AssemblyDirectory) .AddJsonFile("appsettings.json"); var configuration = configurationBuilder.Build(); string SettingsResolver(string name) => configuration[name]; var apiUrl = SettingsResolver("ApiUrl"); var maxDelay = TimeSpan.Parse(SettingsResolver("MaxDelay")); var maxDelayMs = (int)maxDelay.TotalMilliseconds; var rnd = new System.Random(); TraceInformation($"REST API Random Test Client. API Url: {apiUrl}"); var apiClient = new HttpClient(); while (true) { var c = GetRandomCommand(); TraceInformation($"Processing command {c}"); var request = GetRequest(c, apiUrl); try { TraceInformation($"{request.Method} {request.RequestUri}"); var response = apiClient.SendAsync(request).Result; TraceResponse(response, request.Method, request.RequestUri); Thread.Sleep(rnd.Next(maxDelayMs)); } catch (Exception ex) { TraceError($"Failed to process command {c}: {ex.GetAllMessages()}"); } } } // ReSharper disable once FunctionNeverReturns }
static void Main(string[] args) { using (DiagnosticPipeline pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json")) { // Build up the pipeline Console.WriteLine("Pipeline is created."); // Send a trace to the pipeline Trace.TraceInformation("This is a message from trace . . ."); MyEventSource.Log.Message("This is a message from EventSource ..."); // Make a simple get request to bing.com just to generate some HTTP trace HttpClient client = new HttpClient(); client.GetStringAsync("http://www.bing.com").Wait(); // Check the result Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(true); } }
public void ShouldUseDefaultHealthReporterIfNotSpecified() { string pipelineConfiguration = @" { ""inputs"": [ { ""type"": ""EventSource"", ""sources"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, ] } ], ""outputs"": [ { ""type"": ""StdOutput"", } ], ""schemaVersion"": ""2016-08-11"", }"; try { using (var configFile = new TemporaryFile()) { configFile.Write(pipelineConfiguration); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile(configFile.FilePath); var configuration = builder.Build(); using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(configuration)) { Assert.NotNull(pipeline); Assert.True(pipeline.HealthReporter is CsvHealthReporter); } } } finally { TryDeleteFile(CsvHealthReporter.DefaultLogFilePrefix, delayMilliseconds: 500); } }
public async Task SendEventSourceMessages() { string cluster = "ClusterName"; string appType = "ApplicationTypeName"; string appVer = "ApplicationVersion"; string appInst = "ApplicationInstanceName"; string pkgPath = @"c:\"; string error = "Error"; string status = "Status"; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowTestConfig.json")) { ServiceEventSource.Current.ApplicationDeploymentCompleted(15000, true, cluster, appType, appVer, appInst); ServiceEventSource.Current.ApplicationDeploymentSuccessStatus(cluster, appType, appVer, appInst, status); ServiceEventSource.Current.ApplicationDeploymentFailureCopyFailure(cluster, appType, appVer, appInst, pkgPath, error); ServiceEventSource.Current.ApplicationDeploymentFailureCorruptPackage(cluster, appType, appVer, appInst, pkgPath, error); ServiceEventSource.Current.ApplicationDeploymentFailureAlreadyRegistered(cluster, appType, appVer, appInst, pkgPath); ServiceEventSource.Current.ApplicationDeploymentFailureTransientError(cluster, appType, appVer, appInst, pkgPath, status, error); ServiceEventSource.Current.ApplicationDeploymentFailureUnknownError(cluster, appType, appVer, appInst, pkgPath, error); } }
/// <summary> /// Overwrites OMS configuration for local development with OMS Workspace Id/Key from Dev01 /// </summary> /// <param name="provider"></param> /// <returns></returns> private static DiagnosticPipeline CreatePipelineWithStaticOverrides(string workspaceKey, string workspaceId) { string configFilePath = Path.Combine(".\\eventFlowConfig.json"); if (!File.Exists(configFilePath)) { throw new FileNotFoundException("Cannot find eventFlowConfig.json", configFilePath); } IConfiguration config = new ConfigurationBuilder().AddJsonFile(configFilePath).Build(); IConfiguration omsOutput = config.GetSection("outputs").GetChildren().FirstOrDefault(c => c["type"] == "OmsOutput"); if (omsOutput != null) { omsOutput["workspaceKey"] = workspaceKey; omsOutput["workspaceId"] = workspaceId; } return(DiagnosticPipelineFactory.CreatePipeline(config)); }
public void AddsMetadataToExceptionTelemetry() { UnitTestOutput unitTestOutput = null; DateTimeOffset now = DateTimeOffset.Now; using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(diagnosticPipelineConfiguration_.Value)) { unitTestOutput = pipeline.Sinks.First().Output as UnitTestOutput; TelemetryConfiguration telemetryConfiguration = GetAppInsightsTestTelemetryConfiguration(); EventFlowTelemetryProcessor efTelemetryProcessor = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors.OfType <EventFlowTelemetryProcessor>().First(); efTelemetryProcessor.Pipeline = pipeline; TelemetryClient client = new TelemetryClient(telemetryConfiguration); try { throw new Exception("Bummer!"); } catch (Exception e) { ExceptionTelemetry et = new ExceptionTelemetry(e); et.Timestamp = now; client.TrackException(et); } } Assert.Equal(1, unitTestOutput.EventCount); Assert.True(unitTestOutput.CapturedEvents.TryDequeue(out EventData eventData)); Assert.Equal(now, eventData.Timestamp); Assert.True(eventData.TryGetMetadata(ExceptionData.ExceptionMetadataKind, out IReadOnlyCollection <EventMetadata> eventMetadata)); Assert.Equal(1, eventMetadata.Count); EventMetadata exceptionMetadata = eventMetadata.ElementAt(0); Assert.Equal(DataRetrievalResult.Success, ExceptionData.TryGetData(eventData, exceptionMetadata, out ExceptionData exceptionData)); Assert.Equal("Bummer!", exceptionData.Exception.Message); }
static void Main(string[] args) { using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(".\\eventFlowConfig.json")) { var factory = new LoggerFactory() .AddEventFlow(pipeline); var logger = new Logger <Program>(factory); logger.LogInformation("Hello from {friend} for {family}!", "LoggerInput", "EventFlow"); long iterations = 0; Guid correlationId = Guid.NewGuid(); while (iterations++ <= 6) { logger.LogInformation($"Correlation Id is {correlationId} which is good.", correlationId); logger.LogDebug("Some stuff happened {context}", new MyContext(correlationId, $"My context description {iterations}", DateTime.Now)); logger.LogDebug("Some more stuff happened {context}", new Dictionary <string, string>() { { nameof(correlationId), $"My context description {iterations}" } }); logger.LogWarning("Warn about other stuff {context}", new { correlationId = $"My context description {iterations}", startTime = DateTime.Now }); } try { throw new Exception("Something really bad happened"); } catch (Exception e) { logger.LogError(e, "Testing logger.Error(e, message, context) {context}", new { CorrelationId = correlationId }); logger.LogInformation(e, "Testing logger.Information(e, message, context) {context}", new { CorrelationId = correlationId }); logger.LogInformation("Testing logger.Information(message, context) {context}", new { CorrelationId = correlationId }); } Console.ReadLine(); } }
public void CanCreateAllStandardPipelineItems() { #if NET46 string pipelineConfiguration = @" { ""inputs"": [ { ""type"": ""EventSource"", ""sources"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, ] }, { ""type"": ""Microsoft.Extensions.Logging"" }, { ""type"": ""Trace"" }, { ""type"": ""Serilog"" }, { ""type"": ""NLog"" }, { ""type"": ""Log4net"", ""LogLevel"": ""Verbose"" }, { ""type"": ""PerformanceCounter"", ""counters"": [ { ""counterCategory"": ""Process"", ""counterName"": ""Private Bytes"" } ] }, { ""type"": ""ETW"", ""providers"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, ] } ], ""outputs"": [ { ""type"": ""StdOutput"", }, { ""type"": ""ElasticSearch"", ""serviceUri"": ""https://*****:*****@" { ""inputs"": [ { ""type"": ""EventSource"", ""sources"": [ { ""providerName"": ""Microsoft-ServiceFabric-Services"" }, ] }, { ""type"": ""Microsoft.Extensions.Logging"" }, { ""type"": ""Trace"" }, { ""type"": ""Serilog"" }, { ""type"": ""NLog"" }, { ""type"": ""Log4net"", ""LogLevel"": ""Verbose"" } ], ""outputs"": [ { ""type"": ""StdOutput"", }, { ""type"": ""ElasticSearch"", ""serviceUri"": ""https://myElasticSearchCluster:9200"", ""eventDocumentTypeName"": ""diagData"" }, { ""type"": ""OmsOutput"", ""workspaceId"": ""00000000-0000-0000-0000-000000000000"", ""workspaceKey"": ""Tm90IGEgd29ya3NwYWNlIGtleQ=="" } ], ""schemaVersion"": ""2016-08-11"" }"; #endif try { using (var configFile = new TemporaryFile()) { configFile.Write(pipelineConfiguration); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile(configFile.FilePath); var configuration = builder.Build(); using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(configuration)) { Assert.NotNull(pipeline); Assert.Collection(pipeline.Inputs, i => Assert.IsType <EventSourceInput>(i), i => Assert.IsType <LoggerInput>(i), i => Assert.IsType <TraceInput>(i), i => Assert.IsType <SerilogInput>(i), i => Assert.IsType <NLogInput>(i), i => Assert.IsType <Log4netInput>(i) #if NET46 , i => Assert.IsType <PerformanceCounterInput>(i) , i => Assert.IsType <EtwInput>(i) #endif ); Assert.Collection(pipeline.Sinks, s => Assert.IsType <StdOutput>(s.Output), s => Assert.IsType <ElasticSearchOutput>(s.Output), s => Assert.IsType <OmsOutput>(s.Output) #if NET46 , s => Assert.IsType <EventHubOutput>(s.Output) , s => Assert.IsType <ApplicationInsightsOutput>(s.Output) #endif ); } } } finally { TryDeleteFile(CsvHealthReporter.DefaultLogFilePrefix, delayMilliseconds: 500); } }