Skip to content
This repository has been archived by the owner on Mar 26, 2019. It is now read-only.

Commit

Permalink
#187 using liblog within app metrics rather than microsoft logging
Browse files Browse the repository at this point in the history
  • Loading branch information
alhardy committed Aug 26, 2017
1 parent f0d7788 commit 6e3af5c
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 57 deletions.
8 changes: 7 additions & 1 deletion sandbox/MetricsInfluxDBSandbox/Host.cs
Expand Up @@ -16,6 +16,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Serilog;

namespace MetricsInfluxDBSandbox
{
Expand Down Expand Up @@ -132,7 +133,12 @@ private static void RecordMetrics(IMetrics metrics)

private static void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.LiterateConsole()
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();

services.AddMetricsReportingCore().AddInfluxDB(InfluxDbUri, InfluxDbDatabase);
services.AddMetricsCore()
.AddClockType<StopwatchClock>()
Expand Down
5 changes: 3 additions & 2 deletions sandbox/MetricsInfluxDBSandbox/MetricsInfluxDBSandbox.csproj
Expand Up @@ -15,8 +15,9 @@
<ItemGroup>
<PackageReference Include="App.Metrics" Version="$(AppMetricsCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Serilog.Sinks.Literate" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="3.3.3" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 0 additions & 6 deletions sandbox/MetricsInfluxDBSandbox/appsettings.json
Expand Up @@ -6,11 +6,5 @@
"GlobalTags": { "env": "stage" },
"ApdexTSeconds": 0.1,
"OAuth2TrackingEnabled": true
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Expand Up @@ -8,16 +8,6 @@
<PackageTags>appmetrics;reporting;influxdb</PackageTags>
</PropertyGroup>

<ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json" Link="stylecop.json" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.0.0">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\App.Metrics.Formatters.InfluxDB\App.Metrics.Formatters.InfluxDB.csproj" />
</ItemGroup>
Expand Down
Expand Up @@ -7,24 +7,24 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using App.Metrics.Logging;
using App.Metrics.Reporting.InfluxDB.Internal;
using Microsoft.Extensions.Logging;

namespace App.Metrics.Reporting.InfluxDB.Client
{
public class DefaultLineProtocolClient : ILineProtocolClient
{
private static readonly ILog Logger = LogProvider.For<DefaultLineProtocolClient>();

private static long _backOffTicks;
private static long _failureAttempts;
private static long _failuresBeforeBackoff;
private static TimeSpan _backOffPeriod;

private readonly HttpClient _httpClient;
private readonly InfluxDBOptions _influxDbOptions;
private readonly ILogger<DefaultLineProtocolClient> _logger;

public DefaultLineProtocolClient(
ILogger<DefaultLineProtocolClient> logger,
InfluxDBOptions influxDbOptions,
HttpPolicy httpPolicy,
HttpClient httpClient)
Expand All @@ -34,7 +34,6 @@ public class DefaultLineProtocolClient : ILineProtocolClient
_backOffPeriod = httpPolicy?.BackoffPeriod ?? throw new ArgumentNullException(nameof(httpPolicy));
_failuresBeforeBackoff = httpPolicy.FailuresBeforeBackoff;
_failureAttempts = 0;
_logger = logger;
}

public async Task<LineProtocolWriteResult> WriteAsync(
Expand Down Expand Up @@ -62,19 +61,19 @@ public class DefaultLineProtocolClient : ILineProtocolClient
Interlocked.Increment(ref _failureAttempts);

var errorMessage = $"Failed to write to InfluxDB - StatusCode: {response.StatusCode} Reason: {response.ReasonPhrase}";
_logger.LogError(LoggingEvents.InfluxDbWriteError, errorMessage);
Logger.Error(errorMessage);

return new LineProtocolWriteResult(false, errorMessage);
}

_logger.LogTrace("Successful write to InfluxDB");
Logger.Trace("Successful write to InfluxDB");

return new LineProtocolWriteResult(true);
}
catch (Exception ex)
{
Interlocked.Increment(ref _failureAttempts);
_logger.LogError(LoggingEvents.InfluxDbWriteError, ex, "Failed to write to InfluxDB");
Logger.Error(ex, "Failed to write to InfluxDB");
return new LineProtocolWriteResult(false, ex.ToString());
}
}
Expand All @@ -86,7 +85,7 @@ private bool NeedToBackoff()
return false;
}

_logger.LogError($"InfluxDB write backoff for {_backOffPeriod.Seconds} secs");
Logger.Error($"InfluxDB write backoff for {_backOffPeriod.Seconds} secs");

if (Interlocked.Read(ref _backOffTicks) == 0)
{
Expand Down
Expand Up @@ -13,7 +13,6 @@
using App.Metrics.Reporting.InfluxDB.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

// ReSharper disable CheckNamespace
Expand Down Expand Up @@ -100,12 +99,10 @@ internal static void AddInfluxDBReportingServices(IServiceCollection services, U
services.TryAddSingleton<ILineProtocolClient>(
provider =>
{
var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
var optionsAccessor = provider.GetRequiredService<IOptions<MetricsReportingInfluxDBOptions>>();
var httpClient = CreateHttpClient(optionsAccessor.Value.InfluxDB, optionsAccessor.Value.HttpPolicy);
return new DefaultLineProtocolClient(
loggerFactory.CreateLogger<DefaultLineProtocolClient>(),
optionsAccessor.Value.InfluxDB,
optionsAccessor.Value.HttpPolicy,
httpClient);
Expand Down
11 changes: 0 additions & 11 deletions src/App.Metrics.Reporting.InfluxDB/Internal/LoggingEvents.cs

This file was deleted.

Expand Up @@ -14,7 +14,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(TestSdkVersion)" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="$(AspNetCoreVersion)" />
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionsVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
<PackageReference Include="xunit" Version="$(XunitVersion)" />
Expand Down
Expand Up @@ -11,7 +11,6 @@
using App.Metrics.Reporting.InfluxDB.Client;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using Moq.Protected;
using Xunit;
Expand All @@ -21,13 +20,6 @@ namespace App.Metrics.Reporting.InfluxDB.Facts
public class DefaultLineProtocolClientTests
{
private static readonly string Payload = "test__test_counter,mtype=counter,unit=none value=1i 1483232461000000000\n";
private readonly ILogger<DefaultLineProtocolClient> _logger;

public DefaultLineProtocolClientTests()
{
var loggerFactory = new LoggerFactory();
_logger = loggerFactory.CreateLogger<DefaultLineProtocolClient>();
}

[Fact]
public async Task Can_write_payload_successfully()
Expand All @@ -45,7 +37,7 @@ public async Task Can_write_payload_successfully()
};
var policy = new HttpPolicy();
var httpClient = MetricsReportingInfluxDBServiceCollectionExtensions.CreateHttpClient(settings, policy, httpMessageHandlerMock.Object);
var influxClient = new DefaultLineProtocolClient(_logger, settings, policy, httpClient);
var influxClient = new DefaultLineProtocolClient(settings, policy, httpClient);

var response = await influxClient.WriteAsync(Payload, CancellationToken.None);

Expand All @@ -71,7 +63,7 @@ public async Task Can_write_payload_successfully_with_creds()

var policy = new HttpPolicy();
var httpClient = MetricsReportingInfluxDBServiceCollectionExtensions.CreateHttpClient(settings, policy, httpMessageHandlerMock.Object);
var influxClient = new DefaultLineProtocolClient(_logger, settings, policy, httpClient);
var influxClient = new DefaultLineProtocolClient(settings, policy, httpClient);

var response = await influxClient.WriteAsync(Payload, CancellationToken.None);

Expand All @@ -89,7 +81,7 @@ public void Http_policy_is_required()
Database = "influx"
};
var client = new DefaultLineProtocolClient(_logger, settings, null, new HttpClient());
var client = new DefaultLineProtocolClient(settings, null, new HttpClient());
};

action.ShouldThrow<ArgumentNullException>();
Expand All @@ -100,7 +92,7 @@ public void Influxdb_settings_are_required()
{
Action action = () =>
{
var client = new DefaultLineProtocolClient(_logger, null, new HttpPolicy(), new HttpClient());
var client = new DefaultLineProtocolClient(null, new HttpPolicy(), new HttpClient());
};

action.ShouldThrow<ArgumentNullException>();
Expand All @@ -122,7 +114,7 @@ public async Task Should_back_off_when_reached_max_failures()
Database = "influx"
};
var httpClient = MetricsReportingInfluxDBServiceCollectionExtensions.CreateHttpClient(settings, policy, httpMessageHandlerMock.Object);
var influxClient = new DefaultLineProtocolClient(_logger, settings, policy, httpClient);
var influxClient = new DefaultLineProtocolClient(settings, policy, httpClient);

foreach (var attempt in Enumerable.Range(0, 10))
{
Expand Down Expand Up @@ -165,7 +157,7 @@ public async Task Should_back_off_when_reached_max_failures_then_retry_after_bac
Database = "influx"
};
var httpClient = MetricsReportingInfluxDBServiceCollectionExtensions.CreateHttpClient(settings, policy, httpMessageHandlerMock.Object);
var influxClient = new DefaultLineProtocolClient(_logger, settings, policy, httpClient);
var influxClient = new DefaultLineProtocolClient(settings, policy, httpClient);

foreach (var attempt in Enumerable.Range(0, 10))
{
Expand Down Expand Up @@ -198,7 +190,7 @@ public async Task Should_back_off_when_reached_max_failures_then_retry_after_bac
ItExpr.IsAny<CancellationToken>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

httpClient = MetricsReportingInfluxDBServiceCollectionExtensions.CreateHttpClient(settings, policy, httpMessageHandlerMock.Object);
influxClient = new DefaultLineProtocolClient(_logger, settings, policy, httpClient);
influxClient = new DefaultLineProtocolClient(settings, policy, httpClient);

var response = await influxClient.WriteAsync(Payload, CancellationToken.None);

Expand Down

0 comments on commit 6e3af5c

Please sign in to comment.