Skip to content

Commit

Permalink
Reduce logging in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed Dec 27, 2024
1 parent 73d477e commit 00a06e3
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Bogus;
using DotNet.Testcontainers.Containers;
using Eventuous.TestHelpers;
using Eventuous.TestHelpers.TUnit.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using TUnit.Core.Interfaces;
Expand All @@ -26,8 +25,6 @@ public virtual async Task InitializeAsync() {

var services = new ServiceCollection();

services.AddLogging(cfg => cfg.ForTests());

Serializer = new DefaultEventSerializer(TestPrimitives.DefaultOptions, TypeMapper);
services.AddSingleton(Serializer);
services.AddSingleton(TypeMapper);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected override void SetupServices(IServiceCollection services) {

var host = services.First(x => !x.IsKeyedService && x.ImplementationFactory?.GetType() == typeof(Func<IServiceProvider, SubscriptionHostedService>));
services.Remove(host);
services.AddLogging(b => ConfigureLogging(b.ForTests(_logLevel)));
services.AddLogging(b => ConfigureLogging(b.ForTests(_logLevel)).SetMinimumLevel(_logLevel));
}

protected override void GetDependencies(IServiceProvider provider) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Eventuous.Tests.Subscriptions;
public class SequenceTests {
public SequenceTests() {
var factory = new LoggerFactory();
factory.AddProvider(new TUnitLoggerProvider());
factory.AddProvider(new TUnitLoggerProvider(LogLevel.Information));
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(factory);
var provider = services.BuildServiceProvider();
Expand Down
2 changes: 1 addition & 1 deletion src/Core/test/Eventuous.Tests.Subscriptions/TestContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static class TestContext {
CancellationToken.None
)
)
.RuleFor(x => x.LogContext, (_, _) => new("test", new LoggerFactory().AddTUnit()));
.RuleFor(x => x.LogContext, (_, _) => new("test", new LoggerFactory().AddTUnit(LogLevel.Information)));

public static MessageConsumeContext CreateContext() => Auto.Generate();
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ public TracesTests() : base(new()) {
_listener = new() {
ShouldListenTo = _ => true,
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllData,
ActivityStarted = activity => Log.LogInformation(
ActivityStarted = activity => Log.LogTrace(
"Started {Activity} with {Id}, parent {ParentId}",
activity.DisplayName,
activity.Id,
activity.ParentId
),
ActivityStopped = activity => Log.LogInformation("Stopped {Activity}", activity.DisplayName)
ActivityStopped = activity => Log.LogTrace("Stopped {Activity}", activity.DisplayName)
};

ActivitySource.AddActivityListener(_listener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public abstract class LegacySubscriptionFixture<T>: IAsyncInitializer, IAsyncDis
protected TestCheckpointStore CheckpointStore { get; } = new();
protected StreamSubscription Subscription { get; set; } = null!;

protected LegacySubscriptionFixture(T handler, StreamName? stream = null, LogLevel logLevel = LogLevel.Debug) {
protected LegacySubscriptionFixture(T handler, StreamName? stream = null, LogLevel logLevel = LogLevel.Information) {
if (stream is { } s) Stream = s;

LoggerFactory = LoggingExtensions.GetLoggerFactory(logLevel);
Expand Down
33 changes: 20 additions & 13 deletions test/Eventuous.TestHelpers.TUnit/Logging/LoggingExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,40 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;

namespace Eventuous.TestHelpers.TUnit.Logging;

public static class LoggingExtensions {
public static ILoggerFactory GetLoggerFactory(LogLevel logLevel = LogLevel.Debug)
public static ILoggerFactory GetLoggerFactory(LogLevel logLevel = LogLevel.Information)
=> LoggerFactory.Create(
builder => builder
.SetMinimumLevel(logLevel)
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("Grpc", LogLevel.Warning)
.AddTUnit()
.AddTUnit(logLevel)
);
public static ILoggerFactory AddTUnit(this ILoggerFactory factory) {
factory.AddProvider(new TUnitLoggerProvider());

public static ILoggerFactory AddTUnit(this ILoggerFactory factory, LogLevel logLevel) {
factory.AddProvider(new TUnitLoggerProvider(logLevel));

return factory;
}

public static ILoggingBuilder AddTUnit(this ILoggingBuilder builder) => builder.AddProvider(new TUnitLoggerProvider());

public static ILoggingBuilder ForTests(this ILoggingBuilder builder, LogLevel logLevel = LogLevel.Information)
=> builder.AddTUnit().SetMinimumLevel(logLevel).AddFilter("Grpc", LogLevel.Warning).AddFilter("Microsoft", LogLevel.Warning);
public static ILoggingBuilder AddTUnit(this ILoggingBuilder builder, LogLevel logLevel) => builder.AddProvider(new TUnitLoggerProvider(logLevel));

public static ILoggingBuilder ForTests(this ILoggingBuilder builder, LogLevel logLevel = LogLevel.Information)
=> builder
.AddTUnit(logLevel)
.SetMinimumLevel(logLevel)
.AddFilter("Grpc", LogLevel.Warning)
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("Npgsql", LogLevel.Warning);
}

public sealed class TUnitLoggerProvider() : ILoggerProvider {
private readonly LoggerExternalScopeProvider _scopeProvider = new();
public sealed class TUnitLoggerProvider(LogLevel logLevel) : ILoggerProvider {
private readonly LoggerExternalScopeProvider _scopeProvider = new();
private readonly ConcurrentDictionary<string, TUnitLog> _loggers = new(StringComparer.OrdinalIgnoreCase);

public ILogger CreateLogger(string categoryName) => new TUnitLog(_scopeProvider);
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new(_scopeProvider, name, logLevel));

public void Dispose() { }
public void Dispose() => _loggers.Clear();
}
13 changes: 7 additions & 6 deletions test/Eventuous.TestHelpers.TUnit/Logging/TUnitLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

namespace Eventuous.TestHelpers.TUnit.Logging;

public class TUnitLog(LoggerExternalScopeProvider scopeProvider) : ILogger {
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
public class TUnitLog(LoggerExternalScopeProvider scopeProvider, string category, LogLevel logLevel) : ILogger {
public bool IsEnabled(LogLevel level) => level >= logLevel;

public IDisposable? BeginScope<TState>(TState state) where TState : notnull => scopeProvider.Push(state);

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) {
if (TestContext.Current == null) return;

var level = logLevel switch {
public void Log<TState>(LogLevel l, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) {
if (TestContext.Current == null || !IsEnabled(l)) return;

var level = l switch {
LogLevel.Trace => global::TUnit.Core.Logging.LogLevel.Trace,
LogLevel.Debug => global::TUnit.Core.Logging.LogLevel.Debug,
LogLevel.Information => global::TUnit.Core.Logging.LogLevel.Information,
Expand All @@ -21,6 +22,6 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
LogLevel.Critical => global::TUnit.Core.Logging.LogLevel.Critical,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel))
};
TestContext.Current.GetDefaultLogger().Log(level, state, exception, formatter);
TestContext.Current.OutputWriter.WriteLine($"[{category}] {level}: {formatter(state, exception)}");
}
}

0 comments on commit 00a06e3

Please sign in to comment.