Skip to content

Commit

Permalink
Merge pull request #58 from mattwcole/csharp9
Browse files Browse the repository at this point in the history
Csharp9
  • Loading branch information
mattwcole committed Feb 16, 2021
2 parents 0a03547 + 09d255e commit 7fecab8
Show file tree
Hide file tree
Showing 17 changed files with 52 additions and 51 deletions.
2 changes: 1 addition & 1 deletion docker-compose.ci.build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: '3'

services:
ci-build:
image: mcr.microsoft.com/dotnet/core/sdk:3.0
image: mcr.microsoft.com/dotnet/sdk:5.0
volumes:
- .:/src
working_dir: /src
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.ci.publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: '3'

services:
ci-build:
image: mcr.microsoft.com/dotnet/core/sdk:3.0
image: mcr.microsoft.com/dotnet/sdk:5.0
volumes:
- .:/src
working_dir: /src
Expand Down
2 changes: 1 addition & 1 deletion src/Gelf.Extensions.Logging/Gelf.Extensions.Logging.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<VersionPrefix>0.1.0</VersionPrefix>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Expand Down
4 changes: 2 additions & 2 deletions src/Gelf.Extensions.Logging/GelfLogScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ namespace Gelf.Extensions.Logging
{
public class GelfLogScope
{
private static readonly AsyncLocal<GelfLogScope?> Value = new();

private GelfLogScope(IEnumerable<KeyValuePair<string, object>> additionalFields)
{
AdditionalFields = additionalFields;
Expand All @@ -15,8 +17,6 @@ private GelfLogScope(IEnumerable<KeyValuePair<string, object>> additionalFields)

public IEnumerable<KeyValuePair<string, object>> AdditionalFields { get; }

private static readonly AsyncLocal<GelfLogScope?> Value = new AsyncLocal<GelfLogScope?>();

public static GelfLogScope? Current
{
get => Value.Value;
Expand Down
25 changes: 13 additions & 12 deletions src/Gelf.Extensions.Logging/GelfLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ namespace Gelf.Extensions.Logging
{
public class GelfLogger : ILogger
{
private static readonly Regex AdditionalFieldKeyRegex = new Regex(@"^[\w\.\-]*$", RegexOptions.Compiled);
private static readonly Regex AdditionalFieldKeyRegex = new(@"^[\w\.\-]*$", RegexOptions.Compiled);

private static readonly HashSet<string> ReservedAdditionalFieldKeys = new HashSet<string>
private static readonly HashSet<string> ReservedAdditionalFieldKeys = new()
{
"id",
"logger",
Expand All @@ -34,7 +34,7 @@ public GelfLogger(string name, GelfMessageProcessor messageProcessor, GelfLogger
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
Expand All @@ -52,7 +52,7 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
};

var additionalFields = _options.AdditionalFields
.Concat(GetComputedAdditionalFieldsFromAdditionalFieldsFactory(logLevel, eventId, exception))
.Concat(GetFactoryAdditionalFields(logLevel, eventId, exception))
.Concat(GetScopeAdditionalFields())
.Concat(GetStateAdditionalFields(state));

Expand Down Expand Up @@ -102,11 +102,11 @@ static IDisposable BeginValueTupleScope((string, object) field)
}
}

private static IEnumerable<KeyValuePair<string, object>> GetStateAdditionalFields<TState>(TState state)
private IEnumerable<KeyValuePair<string, object>> GetFactoryAdditionalFields(
LogLevel logLevel, EventId eventId, Exception? exception)
{
return state is IEnumerable<KeyValuePair<string, object>> logValues
? logValues
: Enumerable.Empty<KeyValuePair<string, object>>();
return _options.AdditionalFieldsFactory?.Invoke(logLevel, eventId, exception) ??
Enumerable.Empty<KeyValuePair<string, object>>();
}

private IEnumerable<KeyValuePair<string, object>> GetScopeAdditionalFields()
Expand All @@ -128,10 +128,11 @@ private IEnumerable<KeyValuePair<string, object>> GetScopeAdditionalFields()
return additionalFields.Reverse();
}

private IEnumerable<KeyValuePair<string, object>> GetComputedAdditionalFieldsFromAdditionalFieldsFactory(LogLevel logLevel, EventId eventId, Exception? exception)
private static IEnumerable<KeyValuePair<string, object>> GetStateAdditionalFields<TState>(TState state)
{
return _options.AdditionalFieldsFactory.Invoke(logLevel, eventId, exception) ??
Enumerable.Empty<KeyValuePair<string, object>>();
return state is IEnumerable<KeyValuePair<string, object>> logValues
? logValues
: Enumerable.Empty<KeyValuePair<string, object>>();
}

private IEnumerable<KeyValuePair<string, object>> ValidateAdditionalFields(
Expand Down Expand Up @@ -185,4 +186,4 @@ public void Dispose()
}
}
}
}
}
9 changes: 4 additions & 5 deletions src/Gelf.Extensions.Logging/GelfLoggerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,17 @@ public class GelfLoggerOptions
/// <summary>
/// Additional fields that will be attached to all log messages.
/// </summary>
public Dictionary<string, object> AdditionalFields { get; set; } = new Dictionary<string, object>();
public Dictionary<string, object> AdditionalFields { get; set; } = new();

/// <summary>
/// Compute additional fields based on raw log data.
/// Additional fields computed based on raw log data.
/// </summary>
public Func<LogLevel, EventId?, Exception?, Dictionary<string, object>?> AdditionalFieldsFactory { get; set; } =
(loglevel, eventId, exception) => new Dictionary<string, object>();
public Func<LogLevel, EventId, Exception?, Dictionary<string, object>>? AdditionalFieldsFactory { get; set; }

/// <summary>
/// Headers used when sending logs via HTTP(S).
/// </summary>
public Dictionary<string, string> HttpHeaders { get; set; } = new Dictionary<string, string>();
public Dictionary<string, string> HttpHeaders { get; set; } = new();

/// <summary>
/// Timeout used when sending logs via HTTP(S).
Expand Down
2 changes: 1 addition & 1 deletion src/Gelf.Extensions.Logging/GelfLoggerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private static IGelfClient CreateGelfClient(GelfLoggerOptions options)
{
return options.Protocol switch
{
GelfProtocol.Udp => (IGelfClient) new UdpGelfClient(options),
GelfProtocol.Udp => new UdpGelfClient(options),
GelfProtocol.Http => new HttpGelfClient(options),
GelfProtocol.Https => new HttpGelfClient(options),
_ => throw new ArgumentException("Unknown protocol.", nameof(options))
Expand Down
2 changes: 1 addition & 1 deletion src/Gelf.Extensions.Logging/GelfMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ public class GelfMessage
public IReadOnlyCollection<KeyValuePair<string, object>> AdditionalFields { get; set; } =
Array.Empty<KeyValuePair<string, object>>();
}
}
}
9 changes: 3 additions & 6 deletions src/Gelf.Extensions.Logging/HttpGelfClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Gelf.Extensions.Logging
public class HttpGelfClient : IGelfClient
{
private readonly HttpClient _httpClient;

public HttpGelfClient(GelfLoggerOptions options)
{
var uriBuilder = new UriBuilder
Expand All @@ -24,12 +24,9 @@ public HttpGelfClient(GelfLoggerOptions options)
Timeout = options.HttpTimeout
};

if (options.HttpHeaders != null)
foreach (var header in options.HttpHeaders)
{
foreach (var header in options.HttpHeaders)
{
_httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
_httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Gelf.Extensions.Logging/LoggerFactoryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace Gelf.Extensions.Logging
public static class LoggerFactoryExtensions
{
/// <summary>
/// Adds a <see cref="GelfLoggerProvider"/> to the logger factory with the supplied
/// <see cref="GelfLoggerOptions"/>.
/// Adds a <see cref="GelfLoggerProvider" /> to the logger factory with the supplied
/// <see cref="GelfLoggerOptions" />.
/// </summary>
/// <param name="loggerFactory"></param>
/// <param name="options"></param>
Expand Down
6 changes: 3 additions & 3 deletions src/Gelf.Extensions.Logging/LoggingBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Gelf.Extensions.Logging
public static class LoggingBuilderExtensions
{
/// <summary>
/// Registers a <see cref="GelfLoggerProvider"/> with the service collection.
/// Registers a <see cref="GelfLoggerProvider" /> with the service collection.
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
Expand All @@ -24,8 +24,8 @@ public static ILoggingBuilder AddGelf(this ILoggingBuilder builder)
}

/// <summary>
/// Registers a <see cref="GelfLoggerProvider"/> with the service collection allowing logger options
/// to be customised.
/// Registers a <see cref="GelfLoggerProvider" /> with the service collection allowing logger options
/// to be customised.
/// </summary>
/// <param name="builder"></param>
/// <param name="configure"></param>
Expand Down
2 changes: 1 addition & 1 deletion test/Gelf.Extensions.Logging.Tests/Fixtures/TestContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Gelf.Extensions.Logging.Tests.Fixtures
{
public static class TestContext
{
private static readonly AsyncLocal<string> LocalTestId = new AsyncLocal<string>();
private static readonly AsyncLocal<string> LocalTestId = new();

public static string TestId
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>latest</LangVersion>
<TargetFramework>netcoreapp5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
15 changes: 9 additions & 6 deletions test/Gelf.Extensions.Logging.Tests/GelfLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using Microsoft.Extensions.Logging;
using Xunit;

// ReSharper disable TemplateIsNotCompileTimeConstantProblem
// ReSharper disable InconsistentLogPropertyNaming

namespace Gelf.Extensions.Logging.Tests
{
public abstract class GelfLoggerTests : IDisposable
Expand Down Expand Up @@ -39,7 +42,7 @@ public async Task Sends_message_to_Graylog(LogLevel logLevel, int expectedLevel)
var messageText = Faker.Lorem.Sentence();
var sut = LoggerFixture.CreateLogger<GelfLoggerTests>();

sut.Log(logLevel, new EventId(), (object) null, null, (s, e) => messageText);
sut.Log(logLevel, new EventId(), (object) null, null, (_, _) => messageText);

var message = await GraylogFixture.WaitForMessageAsync();

Expand Down Expand Up @@ -237,15 +240,15 @@ public async Task Sends_message_templates_when_enabled()
}

[Fact]
public async Task Uses_additional_fields_factory()
public async Task Sends_message_with_additional_fields_from_factory()
{
var options = LoggerFixture.LoggerOptions;
options.AdditionalFieldsFactory = (originalLogLevel, originalEvent, originalException) =>
new Dictionary<string, object>
{
{"log_level", originalLogLevel.ToString()},
{"exception_type", originalException?.GetType().ToString()},
{"custom_event_name", originalEvent?.Name}
["log_level"] = originalLogLevel.ToString(),
["exception_type"] = originalException?.GetType().ToString(),
["custom_event_name"] = originalEvent.Name
};

using var loggerFactory = LoggerFixture.CreateLoggerFactory(options);
Expand All @@ -265,4 +268,4 @@ public async Task Uses_additional_fields_factory()
Assert.Equal("foo", message.custom_event_name);
}
}
}
}
2 changes: 1 addition & 1 deletion test/Gelf.Extensions.Logging.Tests/HttpGelfLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public HttpGelfLoggerTests(HttpGraylogFixture graylogFixture) : base(graylogFixt
Host = GraylogFixture.Host,
Port = graylogFixture.InputPort,
Protocol = GelfProtocol.Http,
LogSource = typeof(HttpGelfLoggerTests).Name
LogSource = nameof(HttpGelfLoggerTests)
}))
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void Reads_GELF_logger_options_from_custom_configuration_section()
[Fact]
public void Reads_GELF_logger_options_with_default_udpmaxchunksize()
{
int defaultMaxChunkSize = 8192;
var defaultMaxChunkSize = 8192;

var configuration = new ConfigurationBuilder().Add(new MemoryConfigurationSource
{
Expand All @@ -91,14 +91,14 @@ public void Reads_GELF_logger_options_with_default_udpmaxchunksize()

using var provider = serviceCollection.BuildServiceProvider();
var options = provider.GetRequiredService<IOptions<GelfLoggerOptions>>();

Assert.Equal(options.Value.UdpMaxChunkSize, defaultMaxChunkSize);
}

[Fact]
public void Reads_GELF_logger_options_with_custom_udpmaxchunksize()
{
int customChunkSize = 1024;
var customChunkSize = 1024;

var configuration = new ConfigurationBuilder().Add(new MemoryConfigurationSource
{
Expand All @@ -125,7 +125,7 @@ public void Reads_GELF_logger_options_with_custom_udpmaxchunksize()
[Fact]
public void Reads_GELF_logger_options_with_custom_udpmaxchunksize_post_configuration()
{
int customChunkSize = 1024;
var customChunkSize = 1024;

var configuration = new ConfigurationBuilder().Add(new MemoryConfigurationSource
{
Expand All @@ -140,7 +140,7 @@ public void Reads_GELF_logger_options_with_custom_udpmaxchunksize_post_configura
var serviceCollection = new ServiceCollection()
.AddLogging(loggingBuilder => loggingBuilder
.AddConfiguration(configuration.GetSection("Logging"))
.AddGelf(o=>o.UdpMaxChunkSize = customChunkSize));
.AddGelf(o => o.UdpMaxChunkSize = customChunkSize));

using var provider = serviceCollection.BuildServiceProvider();
var options = provider.GetRequiredService<IOptions<GelfLoggerOptions>>();
Expand Down
4 changes: 3 additions & 1 deletion test/Gelf.Extensions.Logging.Tests/UdpGelfLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.Extensions.Logging;
using Xunit;

// ReSharper disable TemplateIsNotCompileTimeConstantProblem

namespace Gelf.Extensions.Logging.Tests
{
public class UdpGelfLoggerTests : GelfLoggerTests, IClassFixture<UdpGraylogFixture>
Expand All @@ -13,7 +15,7 @@ public UdpGelfLoggerTests(UdpGraylogFixture graylogFixture) : base(graylogFixtur
Host = GraylogFixture.Host,
Port = graylogFixture.InputPort,
Protocol = GelfProtocol.Udp,
LogSource = typeof(UdpGelfLoggerTests).Name
LogSource = nameof(UdpGelfLoggerTests)
}))
{
}
Expand Down

0 comments on commit 7fecab8

Please sign in to comment.