Beispiel #1
0
        public async Task UsesCustomJsonSerializerSettings()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""InfinityProperty"":""Infinity""}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""InfinityProperty"":0.0}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 79, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
Beispiel #2
0
        public async Task ProducesJsonLinesIfRequested()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                {
                    ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                    ""ProviderName"":""HttpOutputTests"",
                    ""Level"":4,
                    ""Keywords"":0,
                    ""Payload"":{""Message"":""Hey!""}
                }
                {
                    ""Timestamp"":""2018-01-02T14:14:20+00:00"",
                    ""ProviderName"":""HttpOutputTests"",
                    ""Level"":3,
                    ""Keywords"":0,
                    ""Payload"":{""Message"":""Hey!""}
                }";

            expectedContent = RemoveWhitespace(expectedContent);

            await output.SendEventsAsync(events, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => RemoveWhitespace(content.ReadAsStringAsync().GetAwaiter().GetResult()) == expectedContent)
                                      ), Times.Once());
        }
Beispiel #3
0
        public HttpOutput(HttpOutputConfiguration configuration, IHealthReporter healthReporter, Implementation.IHttpClient httpClient = null)
        {
            Requires.NotNull(configuration, nameof(configuration));
            Requires.NotNull(healthReporter, nameof(healthReporter));

            this.healthReporter = healthReporter;

            // Clone the configuration instance since we are going to hold onto it (via this.connectionData)
            Initialize(configuration.DeepClone(), httpClient);
        }
Beispiel #4
0
        private void Initialize(HttpOutputConfiguration configuration, Implementation.IHttpClient httpClient)
        {
            string errorMessage;

            Debug.Assert(configuration != null);
            Debug.Assert(this.healthReporter != null);

            this.httpClient    = httpClient ?? new StandardHttpClient();
            this.configuration = configuration;

            if (string.IsNullOrWhiteSpace(this.configuration.ServiceUri))
            {
                var errMsg = $"{nameof(HttpOutput)}: no ServiceUri configured";
                healthReporter.ReportProblem(errMsg);
                throw new Exception(errMsg);
            }

            string userName = configuration.BasicAuthenticationUserName;
            string password = configuration.BasicAuthenticationUserPassword;
            bool   credentialsIncomplete = string.IsNullOrWhiteSpace(userName) ^ string.IsNullOrWhiteSpace(password);

            if (credentialsIncomplete)
            {
                errorMessage = $"{nameof(configuration)}: for basic authentication to work both user name and password must be specified";
                healthReporter.ReportWarning(errorMessage, EventFlowContextIdentifiers.Configuration);
                userName = password = null;
            }

            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                string httpAuthValue = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password)));
                this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", httpAuthValue);
            }

            switch (this.configuration.Format)
            {
            case HttpOutputFormat.Json:
            case HttpOutputFormat.JsonLines:
                if (string.IsNullOrWhiteSpace(this.configuration.HttpContentType))
                {
                    this.configuration.HttpContentType = "application/json";
                }
                break;
            }

            foreach (KeyValuePair <string, string> header in configuration.Headers)
            {
                this.httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }

            SerializerSettings = EventFlowJsonUtilities.GetDefaultSerializerSettings();
        }
        public HttpOutputConfiguration DeepClone()
        {
            var other = new HttpOutputConfiguration()
            {
                ServiceUri                      = this.ServiceUri,
                Format                          = this.Format,
                HttpContentType                 = this.HttpContentType,
                BasicAuthenticationUserName     = this.BasicAuthenticationUserName,
                BasicAuthenticationUserPassword = this.BasicAuthenticationUserPassword
            };

            return(other);
        }
Beispiel #6
0
        public void VerifyAllConfigOptionsMappedToConfigObject()
        {
            var pipelineConfigObj = new Dictionary <string, object>
            {
                ["outputs"] = new List <Dictionary <string, object> >
                {
                    new Dictionary <string, object>
                    {
                        ["type"]       = "Http",
                        ["format"]     = "JsonLines",
                        ["ServiceUri"] = "http://localhost:1000",
                        ["basicAuthenticationUserName"]     = "******",
                        ["basicAuthenticationUserPassword"] = "******",
                        ["httpContentType"] = "application/x-custom",
                        ["headers"]         = new Dictionary <string, string>
                        {
                            ["X-Foo"] = "example"
                        }
                    }
                }
            };

            using (var configFile = new TemporaryFile())
            {
                var pipelineConfig = JsonConvert.SerializeObject(pipelineConfigObj, EventFlowJsonUtilities.GetDefaultSerializerSettings());

                configFile.Write(pipelineConfig);
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(configFile.FilePath);
                var configuration       = configBuilder.Build();
                var outputConfigSection = configuration.GetSection("outputs");
                var configFragments     = outputConfigSection.GetChildren().ToList();

                var httpOutputConfiguration = new HttpOutputConfiguration();
                configFragments[0].Bind(httpOutputConfiguration);

                Assert.Equal("http://localhost:1000", httpOutputConfiguration.ServiceUri);
                Assert.Equal(HttpOutputFormat.JsonLines, httpOutputConfiguration.Format);
                Assert.Equal("mywebuser", httpOutputConfiguration.BasicAuthenticationUserName);
                Assert.Equal("mywebpass", httpOutputConfiguration.BasicAuthenticationUserPassword);
                Assert.Equal("application/x-custom", httpOutputConfiguration.HttpContentType);
                Assert.Equal("example", httpOutputConfiguration.Headers["X-Foo"]);
            }
        }
Beispiel #7
0
        public async Task ProducesJsonByDefault()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":4,
                        ""Keywords"":0,
                        ""Payload"":{""Message"":""Hey!""}
                    },
                    {
                        ""Timestamp"":""2018-01-02T14:14:20+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""Message"":""Hey!""}
                    }]";

            expectedContent = RemoveWhitespace(expectedContent);

            await output.SendEventsAsync(events, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
Beispiel #8
0
        public HttpOutput(IConfiguration configuration, IHealthReporter healthReporter, Implementation.IHttpClient httpClient = null)
        {
            Requires.NotNull(configuration, nameof(configuration));
            Requires.NotNull(healthReporter, nameof(healthReporter));

            this.healthReporter = healthReporter;

            var httpOutputConfiguration = new HttpOutputConfiguration();

            try
            {
                configuration.Bind(httpOutputConfiguration);
            }
            catch
            {
                healthReporter.ReportProblem($"Invalid {nameof(HttpOutput)} configuration encountered: '{configuration.ToString()}'",
                                             EventFlowContextIdentifiers.Configuration);
                throw;
            }

            Initialize(httpOutputConfiguration, httpClient);
        }
Beispiel #9
0
        public async Task MethodInfoIsSerializedAsFullyQualifiedName()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""Method"":""Microsoft.Diagnostics.EventFlow.Outputs.Tests.HttpOutputTests.MethodInfoIsSerializedAsFullyQualifiedName""}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
Beispiel #10
0
        public void VerifyAllConfigOptionsMappedToConfigObject()
        {
            var pipelineConfigObj = new Dictionary <string, object>
            {
                ["outputs"] = new List <Dictionary <string, object> >
                {
                    new Dictionary <string, object>
                    {
                        ["type"]       = "Http",
                        ["format"]     = "JsonLines",
                        ["ServiceUri"] = "http://localhost:1000",
                        ["basicAuthenticationUserName"]     = "******",
                        ["basicAuthenticationUserPassword"] = "******",
                        ["httpContentType"] = "application/x-custom",
                    }
                }
            };

            using (var configFile = new TemporaryFile())
            {
                var pipelineConfig = JsonConvert.SerializeObject(pipelineConfigObj);

                configFile.Write(pipelineConfig);
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(configFile.FilePath);
                var configuration       = configBuilder.Build();
                var outputConfigSection = configuration.GetSection("outputs");
                var configFragments     = outputConfigSection.GetChildren().ToList();

                var httpOutputConfiguration = new HttpOutputConfiguration();
                configFragments[0].Bind(httpOutputConfiguration);

                Assert.Equal(httpOutputConfiguration.ServiceUri, "http://localhost:1000");
                Assert.Equal(httpOutputConfiguration.Format, HttpOutputFormat.JsonLines);
                Assert.Equal(httpOutputConfiguration.BasicAuthenticationUserName, "mywebuser");
                Assert.Equal(httpOutputConfiguration.BasicAuthenticationUserPassword, "mywebpass");
                Assert.Equal(httpOutputConfiguration.HttpContentType, "application/x-custom");
            }
        }