From 93294e75df9b679b311d4bb12ca4899cc0768135 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:07:04 +0900 Subject: [PATCH 1/7] Make AddZLogger* flatten --- sandbox/Benchmark/Benchmarks/PostLogEntry.cs | 14 +- .../Benchmarks/WriteJsonToConsole.cs | 7 +- .../Benchmark/Benchmarks/WriteJsonToFile.cs | 13 +- .../Benchmarks/WritePlainTextToConsole.cs | 10 +- .../Benchmarks/WritePlainTextToFile.cs | 16 +- .../InternalBenchmarks/EmptyLogging.cs | 23 +-- sandbox/Benchmark/SimpleBench.cs | 2 +- sandbox/ConsoleApp/ConsoleApp.csproj | 1 + sandbox/ConsoleApp/Program.cs | 26 +-- src/ZLogger/ZLoggerBuilder.cs | 102 ++++++------ .../FormatterTest.cs | 14 +- tests/ZLogger.MessagePack.Tests/ScopeTest.cs | 6 +- .../BatchingAsyncLogProcessorTest.cs | 15 +- tests/ZLogger.Tests/BuilderTest.cs | 28 ++-- tests/ZLogger.Tests/JsonFormatTest.cs | 42 +++-- tests/ZLogger.Tests/NamedParamTest.cs | 2 +- tests/ZLogger.Tests/PlainTextFormatTest.cs | 6 +- tests/ZLogger.Tests/ProviderTest.cs | 150 ++++++++++++++++++ tests/ZLogger.Tests/ScopeTest.cs | 18 +-- tests/ZLogger.Tests/TimestampTest.cs | 17 +- 20 files changed, 286 insertions(+), 226 deletions(-) create mode 100644 tests/ZLogger.Tests/ProviderTest.cs diff --git a/sandbox/Benchmark/Benchmarks/PostLogEntry.cs b/sandbox/Benchmark/Benchmarks/PostLogEntry.cs index 5e717eea..557d6282 100644 --- a/sandbox/Benchmark/Benchmarks/PostLogEntry.cs +++ b/sandbox/Benchmark/Benchmarks/PostLogEntry.cs @@ -2,21 +2,18 @@ using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; -using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Jobs; -using log4net.Repository.Hierarchy; using Microsoft.Extensions.Logging; using NLog; using NLog.Extensions.Logging; using NLog.Targets.Wrappers; using Serilog; using ZLogger; -using ZLogger.Formatters; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Benchmark.Benchmarks; @@ -106,16 +103,9 @@ public void SetUp() var zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(builder => + logging.AddZLoggerStream(Stream.Null, options => { - //builder.AddLogProcessor(new NullProcessor()); - - //builder.AddStream(Stream.Null); - - builder.AddStream(Stream.Null, options => - { - options.UsePlainTextFormatter(formatter => formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel))); - }); + options.UsePlainTextFormatter(formatter => formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel))); }); }); disposables.Add(zLoggerFactory); diff --git a/sandbox/Benchmark/Benchmarks/WriteJsonToConsole.cs b/sandbox/Benchmark/Benchmarks/WriteJsonToConsole.cs index cd27366d..065b7fcd 100644 --- a/sandbox/Benchmark/Benchmarks/WriteJsonToConsole.cs +++ b/sandbox/Benchmark/Benchmarks/WriteJsonToConsole.cs @@ -60,12 +60,9 @@ public void SetUpLogger() zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(builder => + logging.AddZLoggerConsole(console => { - builder.AddConsole(console => - { - console.UseJsonFormatter(); - }); + console.UseJsonFormatter(); }); }); diff --git a/sandbox/Benchmark/Benchmarks/WriteJsonToFile.cs b/sandbox/Benchmark/Benchmarks/WriteJsonToFile.cs index f7fd1e60..d4241dec 100644 --- a/sandbox/Benchmark/Benchmarks/WriteJsonToFile.cs +++ b/sandbox/Benchmark/Benchmarks/WriteJsonToFile.cs @@ -72,16 +72,11 @@ public void SetUpLogger() // ZLogger - zLoggerFactory = LoggerFactory.Create(logging => - { - logging.AddZLogger(builder => + zLoggerFactory = LoggerFactory.Create(logging => logging + .AddZLoggerFile(GetLogFilePath("zlogger.log"), options => { - builder.AddFile(GetLogFilePath("zlogger.log"), options => - { - options.UseJsonFormatter(); - }); - }); - }); + options.UseJsonFormatter(); + })); zLogger = zLoggerFactory.CreateLogger(); diff --git a/sandbox/Benchmark/Benchmarks/WritePlainTextToConsole.cs b/sandbox/Benchmark/Benchmarks/WritePlainTextToConsole.cs index 71bb0e98..aad5c00c 100644 --- a/sandbox/Benchmark/Benchmarks/WritePlainTextToConsole.cs +++ b/sandbox/Benchmark/Benchmarks/WritePlainTextToConsole.cs @@ -55,14 +55,12 @@ public void SetUpLogger() { zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(builder => + logging.AddZLoggerConsole(console => { - builder.AddConsole(console => + console.UsePlainTextFormatter(formatter => { - console.UsePlainTextFormatter(formatter => - { - formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel)); - }); + formatter.SetPrefixFormatter($"{0} [{1}]", + (template, info) => template.Format(info.Timestamp, info.LogLevel)); }); }); }); diff --git a/sandbox/Benchmark/Benchmarks/WritePlainTextToFile.cs b/sandbox/Benchmark/Benchmarks/WritePlainTextToFile.cs index 1509823b..839dad2c 100644 --- a/sandbox/Benchmark/Benchmarks/WritePlainTextToFile.cs +++ b/sandbox/Benchmark/Benchmarks/WritePlainTextToFile.cs @@ -75,17 +75,13 @@ public void SetUpLogger() zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(zLogger => + logging.AddZLoggerFile(GetLogFilePath("zlogger.log"), options => { - zLogger.AddFile(GetLogFilePath("zlogger.log"), - options => - { - options.UsePlainTextFormatter(formatter => - { - formatter.SetPrefixFormatter($"{0} [{1}]", - (template, info) => template.Format(info.Timestamp, info.LogLevel)); - }); - }); + options.UsePlainTextFormatter(formatter => + { + formatter.SetPrefixFormatter($"{0} [{1}]", + (template, info) => template.Format(info.Timestamp, info.LogLevel)); + }); }); }); diff --git a/sandbox/Benchmark/InternalBenchmarks/EmptyLogging.cs b/sandbox/Benchmark/InternalBenchmarks/EmptyLogging.cs index 586463c6..8adc86be 100644 --- a/sandbox/Benchmark/InternalBenchmarks/EmptyLogging.cs +++ b/sandbox/Benchmark/InternalBenchmarks/EmptyLogging.cs @@ -89,38 +89,27 @@ public void SetUpLogger() zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(zLogger => - { - zLogger.AddLogProcessor(new EmptyLogProcessor()); - }); + logging.AddZLoggerLogProcessor(new EmptyLogProcessor()); }); zLogger = zLoggerFactory.CreateLogger(); zLoggerFactory2 = LoggerFactory.Create(logging => { - logging.AddZLogger(z => - { - z.AddLogProcessor(options => new WriteUtf8LogProcessor(options)); - }); + logging.AddZLoggerLogProcessor(options => new WriteUtf8LogProcessor(options)); }); zLogger2 = zLoggerFactory2.CreateLogger(); zLoggerFactory3 = LoggerFactory.Create(logging => { - logging.AddZLogger(z => + logging.AddZLoggerLogProcessor(options => { - z.AddLogProcessor(options => + options.UsePlainTextFormatter(formatter => { - options.UsePlainTextFormatter(formatter => - { - formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel)); - }); - - return new WriteUtf8LogProcessor(options); + formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel)); }); - + return new WriteUtf8LogProcessor(options); }); }); diff --git a/sandbox/Benchmark/SimpleBench.cs b/sandbox/Benchmark/SimpleBench.cs index 2dd9abca..55c072ce 100644 --- a/sandbox/Benchmark/SimpleBench.cs +++ b/sandbox/Benchmark/SimpleBench.cs @@ -61,7 +61,7 @@ protected override Microsoft.Extensions.Logging.ILogger GetLogger() var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(logging => { - logging.AddZLogger(zLogger => zLogger.AddFile("ZLogger.log")); + logging.AddZLoggerFile("ZLogger.log"); //options.AddZLoggerConsole(); }); var serviceProvider = serviceCollection.BuildServiceProvider(); diff --git a/sandbox/ConsoleApp/ConsoleApp.csproj b/sandbox/ConsoleApp/ConsoleApp.csproj index 6998dc9d..f7dca924 100644 --- a/sandbox/ConsoleApp/ConsoleApp.csproj +++ b/sandbox/ConsoleApp/ConsoleApp.csproj @@ -15,6 +15,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/sandbox/ConsoleApp/Program.cs b/sandbox/ConsoleApp/Program.cs index f7964fb3..6dca7ed7 100644 --- a/sandbox/ConsoleApp/Program.cs +++ b/sandbox/ConsoleApp/Program.cs @@ -1,42 +1,20 @@ -using ConsoleAppFramework; -using ZLogger; +using ZLogger; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Hosting; using System.Threading.Tasks; using System; -using Microsoft.Extensions.DependencyInjection; using System.Threading.Channels; -using Utf8StringInterpolation; using System.Collections.Concurrent; using System.Collections.Generic; -using JetBrains.Profiler.Api; -using System.Threading; -using ZLogger.Formatters; -using ZLogger.Internal; -using ZLogger.Providers; -using System.Numerics; -using System.Text.Json; using System.IO.Hashing; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Net.Sockets; using System.Net.Http; using System.Buffers; -using System.Reflection.PortableExecutable; -using System.Net.Mail; -using Microsoft.Extensions.Options; -using Microsoft.Extensions.DependencyInjection.Extensions; - - - var zLoggerFactory = LoggerFactory.Create(logging => { - logging.AddZLogger(zLogger => - { - zLogger.AddLogProcessor(new EmptyLogProcessor()); - }); + logging.AddZLoggerLogProcessor(new EmptyLogProcessor()); }); var zLogger = zLoggerFactory.CreateLogger("my"); diff --git a/src/ZLogger/ZLoggerBuilder.cs b/src/ZLogger/ZLoggerBuilder.cs index ff93f747..61941318 100644 --- a/src/ZLogger/ZLoggerBuilder.cs +++ b/src/ZLogger/ZLoggerBuilder.cs @@ -1,7 +1,7 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; using System.Text; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; using ZLogger.Internal; using ZLogger.Providers; @@ -9,21 +9,11 @@ namespace ZLogger; public static class ZLoggerBuilderExtensions { - public static ILoggingBuilder AddZLogger(this ILoggingBuilder loggingBuilder, Action configure) + public static ILoggingBuilder AddZLoggerConsole(this ILoggingBuilder builder) => builder.AddZLoggerConsole((_, _) => { }); + public static ILoggingBuilder AddZLoggerConsole(this ILoggingBuilder builder, Action configure) => builder.AddZLoggerConsole((options, _) => configure(options)); + public static ILoggingBuilder AddZLoggerConsole(this ILoggingBuilder builder, Action configure) { - var builder = new ZLoggerBuilder(loggingBuilder); - configure.Invoke(builder); - return loggingBuilder; - } -} - -public class ZLoggerBuilder(ILoggingBuilder loggingBuilder) -{ - public ZLoggerBuilder AddConsole() => AddConsole((_, _) => { }); - public ZLoggerBuilder AddConsole(Action configure) => AddConsole((options, _) => configure(options)); - public ZLoggerBuilder AddConsole(Action configure) - { - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerConsoleOptions(); configure(options, serviceProvider); @@ -42,16 +32,18 @@ public ZLoggerBuilder AddConsole(Action return new ZLoggerConsoleLoggerProvider(options); }); - return this; + return builder; } - public ZLoggerBuilder AddInMemory(Action configureProcessor) => AddInMemory(null, (_, _) => { }, configureProcessor); - public ZLoggerBuilder AddInMemory(Action configure, Action configureProcessor) => AddInMemory(null, configure, configureProcessor); - public ZLoggerBuilder AddInMemory(object? processorKey, Action configure, Action configureProcessor) => AddInMemory(processorKey, (o, _) => configure(o), configureProcessor); - public ZLoggerBuilder AddInMemory(object? processorKey, Action configure, Action configureProcessor) + // TODO:空のやつ追加!!Q!! + // TODO: ZloggerOptionsのやつだけ!! + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configureProcessor) => AddZLoggerInMemory(null, (_, _) => { }, configureProcessor); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(null, configure, configureProcessor); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(processorKey, (o, _) => configure(o), configureProcessor); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) { - loggingBuilder.Services.AddKeyedSingleton(processorKey, (_, _) => new InMemoryObservableLogProcessor()); - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddKeyedSingleton(processorKey, (_, _) => new InMemoryObservableLogProcessor()); + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); configure(options, serviceProvider); @@ -63,76 +55,76 @@ public ZLoggerBuilder AddInMemory(object? processorKey, Action AddLogProcessor((_, _) => logProcessor); - public ZLoggerBuilder AddLogProcessor(Func logProcessorFactory) => AddLogProcessor((o, _) => logProcessorFactory(o)); - public ZLoggerBuilder AddLogProcessor(Func logProcessorFactory) + public static ILoggingBuilder AddZLoggerLogProcessor(this ILoggingBuilder builder, IAsyncLogProcessor logProcessor) => builder.AddZLoggerLogProcessor((_, _) => logProcessor); + public static ILoggingBuilder AddZLoggerLogProcessor(this ILoggingBuilder builder, Func logProcessorFactory) => builder.AddZLoggerLogProcessor((o, _) => logProcessorFactory(o)); + public static ILoggingBuilder AddZLoggerLogProcessor(this ILoggingBuilder builder, Func logProcessorFactory) { - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); var processor = logProcessorFactory(options, serviceProvider); return new ZLoggerLogProcessorLoggerProvider(processor, options); }); - - return this; + return builder; } - public ZLoggerBuilder AddStream(Stream stream) => AddStream((_, _) => stream); - public ZLoggerBuilder AddStream(Stream stream, Action configure) => AddStream((o, _) => { configure(o); return stream; }); - public ZLoggerBuilder AddStream(Stream stream, Action configure) => AddStream((o, p) => { configure(o, p); return stream; }); - public ZLoggerBuilder AddStream(Func streamFactory) + public static ILoggingBuilder AddZLoggerStream(this ILoggingBuilder builder, Stream stream) => builder.AddZLoggerStream((_, _) => stream); + public static ILoggingBuilder AddZLoggerStream(this ILoggingBuilder builder, Stream stream, Action configure) => builder.AddZLoggerStream((o, _) => { configure(o); return stream; }); + public static ILoggingBuilder AddZLoggerStream(this ILoggingBuilder builder, Stream stream, Action configure) => builder.AddZLoggerStream((o, p) => { configure(o, p); return stream; }); + public static ILoggingBuilder AddZLoggerStream(this ILoggingBuilder builder, Func streamFactory) { - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); var stream = streamFactory(options, serviceProvider); return new ZLoggerStreamLoggerProvider(stream, options); }); - - return this; + return builder; } - public ZLoggerBuilder AddFile(string fileName) => AddFile((_, _) => fileName); - public ZLoggerBuilder AddFile(string fileName, Action configure) => AddFile((o, _) => { configure(o); return fileName; }); - public ZLoggerBuilder AddFile(string fileName, Action configure) => AddFile((o, p) => { configure(o, p); return fileName; }); - public ZLoggerBuilder AddFile(Func fileNameFactory) + // TODO: filePathにする + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName) => builder.AddZLoggerFile((_, _) => fileName); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName, Action configure) => builder.AddZLoggerFile((o, _) => { configure(o); return fileName; }); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName, Action configure) => builder.AddZLoggerFile((o, p) => { configure(o, p); return fileName; }); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, Func fileNameFactory) { - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); var fileName = fileNameFactory(options, serviceProvider); return new ZLoggerFileLoggerProvider(fileName, options); }); - - return this; + return builder; } - /// DateTimeOffset is date of file open time(UTC), int is number sequence. + // TODO: optionsのやつ追加 + /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files /// Limit size of single file. - public ZLoggerBuilder AddRollingFile(Func fileNameSelector, RollingInterval rollInterval, int rollSizeKB) => AddRollingFile(fileNameSelector, rollInterval, rollSizeKB, (_, _) => { }); + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB) => + builder.AddZLoggerRollingFile(filePathSelector, rollInterval, rollSizeKB, (_, _) => { }); - /// DateTimeOffset is date of file open time(UTC), int is number sequence. + /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files /// Limit size of single file. - public ZLoggerBuilder AddRollingFile(Func fileNameSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) => AddRollingFile(fileNameSelector, rollInterval, rollSizeKB, (o, _) => configure(o)); + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) => + builder.AddZLoggerRollingFile(filePathSelector, rollInterval, rollSizeKB, (o, _) => configure(o)); - /// DateTimeOffset is date of file open time(UTC), int is number sequence. + /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files /// Limit size of single file. - public ZLoggerBuilder AddRollingFile(Func fileNameSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) { - loggingBuilder.Services.AddSingleton(serviceProvider => + builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); configure(options, serviceProvider); - return new ZLoggerRollingFileLoggerProvider(fileNameSelector, rollInterval, rollSizeKB, options); + return new ZLoggerRollingFileLoggerProvider(filePathSelector, rollInterval, rollSizeKB, options); }); - - return this; + return builder; } } diff --git a/tests/ZLogger.MessagePack.Tests/FormatterTest.cs b/tests/ZLogger.MessagePack.Tests/FormatterTest.cs index 4498299d..306dcdbd 100644 --- a/tests/ZLogger.MessagePack.Tests/FormatterTest.cs +++ b/tests/ZLogger.MessagePack.Tests/FormatterTest.cs @@ -22,7 +22,7 @@ public FormatterTest() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(_ => processor)); + x.AddZLoggerLogProcessor(processor); }); logger = loggerFactory.CreateLogger("test"); } @@ -123,7 +123,7 @@ public void LowercaseMutator() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); logger = loggerFactory.CreateLogger("test"); @@ -154,7 +154,7 @@ public void ExcludeLogInfoProperties() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); logger = loggerFactory.CreateLogger("test"); @@ -180,11 +180,9 @@ public void ExcludeAllLogInfo() processor = new TestProcessor(options); - var loggerFactory = LoggerFactory.Create(x => - { - x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); - }); + var loggerFactory = LoggerFactory.Create(x => x + .SetMinimumLevel(LogLevel.Debug) + .AddZLoggerLogProcessor(processor)); logger = loggerFactory.CreateLogger("test"); logger.ZLogInformation(new EventId(1, "TEST"), $"HELLO!"); diff --git a/tests/ZLogger.MessagePack.Tests/ScopeTest.cs b/tests/ZLogger.MessagePack.Tests/ScopeTest.cs index b4c0d697..9194633d 100644 --- a/tests/ZLogger.MessagePack.Tests/ScopeTest.cs +++ b/tests/ZLogger.MessagePack.Tests/ScopeTest.cs @@ -23,7 +23,11 @@ public ScopeTest() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(options => { options.IncludeScopes = true; return processor; })); + x.AddZLoggerLogProcessor(options => + { + options.IncludeScopes = true; + return processor; + }); }); logger = loggerFactory.CreateLogger("test"); } diff --git a/tests/ZLogger.Tests/BatchingAsyncLogProcessorTest.cs b/tests/ZLogger.Tests/BatchingAsyncLogProcessorTest.cs index a880ebe5..3db5b609 100644 --- a/tests/ZLogger.Tests/BatchingAsyncLogProcessorTest.cs +++ b/tests/ZLogger.Tests/BatchingAsyncLogProcessorTest.cs @@ -14,10 +14,7 @@ public void LessThanBatchSize() var options = new ZLoggerOptions(); var batchingProcessor = new TestBatchingProcessor(10, options); - using (var loggerFactory = LoggerFactory.Create(x => - { - x.AddZLogger(zLogger => zLogger.AddLogProcessor(batchingProcessor)); - })) + using (var loggerFactory = LoggerFactory.Create(x => x.AddZLoggerLogProcessor(batchingProcessor))) { var logger = loggerFactory.CreateLogger("test"); @@ -37,10 +34,7 @@ public void OverflowBatchSize() var options = new ZLoggerOptions(); var batchingProcessor = new TestBatchingProcessor(3, options); - using (var loggerFactory = LoggerFactory.Create(x => - { - x.AddZLogger(zLogger => zLogger.AddLogProcessor(batchingProcessor)); - })) + using (var loggerFactory = LoggerFactory.Create(x => x.AddZLoggerLogProcessor(batchingProcessor))) { var logger = loggerFactory.CreateLogger("test"); @@ -60,10 +54,7 @@ public void ErrorProcess() var options = new ZLoggerOptions(); var batchingProcessor = new ErrorBatchingProcessor(1, options); - using (var loggerFactory = LoggerFactory.Create(x => - { - x.AddZLogger(zLogger => zLogger.AddLogProcessor(batchingProcessor)); - })) + using (var loggerFactory = LoggerFactory.Create(x => x.AddZLoggerLogProcessor(batchingProcessor))) { var logger = loggerFactory.CreateLogger("test"); logger.ZLogInformation($"hehehe"); diff --git a/tests/ZLogger.Tests/BuilderTest.cs b/tests/ZLogger.Tests/BuilderTest.cs index d1ed4adf..b8feb73b 100644 --- a/tests/ZLogger.Tests/BuilderTest.cs +++ b/tests/ZLogger.Tests/BuilderTest.cs @@ -22,7 +22,7 @@ public void LogLevelConfiguration() using var loggerFactory = LoggerFactory.Create(x => { x.AddConfiguration(configuration.GetSection("Logging")); - x.AddZLogger(logging => logging.AddConsole()); + x.AddZLoggerConsole(); }); var logger = loggerFactory.CreateLogger(); @@ -44,23 +44,17 @@ public void LogLevelConfiguration_ProviderAlias() new("Logging:ZLoggerInMemory:LogLevel:Default", "Error") }) .Build(); - - using var loggerFactory = LoggerFactory.Create(x => - { - x.AddConfiguration(configuration.GetSection("Logging")); - x.AddZLogger(logging => - { - logging.AddConsole(); - logging.AddInMemory( - "Foo", - (options, services) => { }, - processor => - { - processor.MessageReceived += msg => messages.Add(msg); - }); - }); - }); + using var loggerFactory = LoggerFactory.Create(x => x + .AddConfiguration(configuration.GetSection("Logging")) + .AddZLoggerConsole() + .AddZLoggerInMemory( + "Foo", + (options, services) => { }, + processor => + { + processor.MessageReceived += msg => messages.Add(msg); + })); var logger = loggerFactory.CreateLogger(); diff --git a/tests/ZLogger.Tests/JsonFormatTest.cs b/tests/ZLogger.Tests/JsonFormatTest.cs index dfeb4bf0..6020a531 100644 --- a/tests/ZLogger.Tests/JsonFormatTest.cs +++ b/tests/ZLogger.Tests/JsonFormatTest.cs @@ -18,25 +18,21 @@ public void FormatLogEntry_CustomMetadata() var sourceCodeHash = Guid.NewGuid().ToString(); - var loggerFactory = LoggerFactory.Create(x => - { - x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => + var loggerFactory = LoggerFactory.Create(x => x + .SetMinimumLevel(LogLevel.Debug) + .AddZLoggerStream(ms, options => { - zLogger.AddStream(ms, options => - { - var hashProp = JsonEncodedText.Encode("Hash"); + var hashProp = JsonEncodedText.Encode("Hash"); - options.UseJsonFormatter(formatter => + options.UseJsonFormatter(formatter => + { + formatter.AdditionalFormatter = (writer, _) => { - formatter.AdditionalFormatter = (writer, _) => - { - writer.WriteString(hashProp, sourceCodeHash); - }; - }); + writer.WriteString(hashProp, sourceCodeHash); + }; }); - }); - }); + })); + var logger = loggerFactory.CreateLogger("test"); var tako = 100; @@ -75,7 +71,7 @@ public void FormatLogEntry_ExcludeLogInfoProperties() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -106,7 +102,7 @@ public void FormatLogEntry_ExcludeAllLogInfo() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -141,7 +137,7 @@ public void KeyNameMutator_Lower() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -174,7 +170,7 @@ public void KeyNameMutatorProp1() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -207,7 +203,7 @@ public void KeyNameMutatorProp2() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -241,7 +237,7 @@ public void NestPayload() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -279,7 +275,7 @@ public void ConfigureName() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -314,7 +310,7 @@ public void KeyNameMutator_CallMethod() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); diff --git a/tests/ZLogger.Tests/NamedParamTest.cs b/tests/ZLogger.Tests/NamedParamTest.cs index d25c5d33..b3f75a18 100644 --- a/tests/ZLogger.Tests/NamedParamTest.cs +++ b/tests/ZLogger.Tests/NamedParamTest.cs @@ -18,7 +18,7 @@ public void StructuredLoggingOptions() using var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); diff --git a/tests/ZLogger.Tests/PlainTextFormatTest.cs b/tests/ZLogger.Tests/PlainTextFormatTest.cs index d63e3084..e55a2a51 100644 --- a/tests/ZLogger.Tests/PlainTextFormatTest.cs +++ b/tests/ZLogger.Tests/PlainTextFormatTest.cs @@ -22,7 +22,7 @@ public void OverloadCheck() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); @@ -91,7 +91,7 @@ public void TextOptions() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processsor)); + x.AddZLoggerLogProcessor(processsor); }); var logger = loggerFactory.CreateLogger("test"); @@ -121,7 +121,7 @@ public void CollectionDestructuring() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddLogProcessor(processor)); + x.AddZLoggerLogProcessor(processor); }); var logger = loggerFactory.CreateLogger("test"); diff --git a/tests/ZLogger.Tests/ProviderTest.cs b/tests/ZLogger.Tests/ProviderTest.cs new file mode 100644 index 00000000..ff28e178 --- /dev/null +++ b/tests/ZLogger.Tests/ProviderTest.cs @@ -0,0 +1,150 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace ZLogger.Tests +{ + public class ProviderTest + { + [Fact] + public void FileProvider() + { + const string Path = "ZLoggerTest.log"; + if (File.Exists(Path)) File.Delete(Path); + { + var loggerFactory = LoggerFactory.Create(x => + { + x.SetMinimumLevel(LogLevel.Debug); + x.AddZLoggerFile(Path); + }); + + var logger = loggerFactory.CreateLogger("mytest"); + + logger.LogDebug("foo"); + logger.LogDebug("bar"); + logger.LogDebug("baz"); + + loggerFactory.Dispose(); + + using (var fs = File.OpenText(Path)) + { + fs.ReadLine().Should().Be("foo"); + fs.ReadLine().Should().Be("bar"); + fs.ReadLine().Should().Be("baz"); + fs.ReadLine().Should().BeNull(); + } + } + + { + // append check + + var loggerFactory = LoggerFactory.Create(x => + { + x.SetMinimumLevel(LogLevel.Debug); + x.AddZLoggerFile(Path); + }); + + var logger = loggerFactory.CreateLogger("mytest"); + + logger.LogDebug("abc"); + logger.LogDebug("def"); + logger.LogDebug("ghi"); + + loggerFactory.Dispose(); + + using (var fs = File.OpenText(Path)) + { + fs.ReadLine().Should().Be("foo"); + fs.ReadLine().Should().Be("bar"); + fs.ReadLine().Should().Be("baz"); + fs.ReadLine().Should().Be("abc"); + fs.ReadLine().Should().Be("def"); + fs.ReadLine().Should().Be("ghi"); + fs.ReadLine().Should().BeNull(); + } + } + + } + + static StreamReader OpenFile(string path) + { + return new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); + } + + [Fact] + public async Task RollingFileProvider() + { + { + var now = new DateTime(2000, 12, 12); + + var path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-0.log"; + if (File.Exists(path)) File.Delete(path); + + var loggerFactory = LoggerFactory.Create(x => + { + x.SetMinimumLevel(LogLevel.Debug); + x.AddZLoggerRollingFile( + (dt, seq) => $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-{seq}.log", + x => now, 5); + }); + + var logger = loggerFactory.CreateLogger("mytest"); + + logger.LogDebug("foo"); + logger.LogDebug("bar"); + logger.LogDebug("baz"); + + await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush + + File.Exists(path).Should().BeTrue(); + var path1 = path; + + // roll next file + now = now.AddDays(1); + path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-0.log"; + if (File.Exists(path)) File.Delete(path); + + logger.LogDebug("a"); + logger.LogDebug("v"); + logger.LogDebug("c"); + + await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush + + File.Exists(path).Should().BeTrue(); + var path2 = path; + + // roll by filesize + path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-1.log"; + if (File.Exists(path)) File.Delete(path); + + logger.LogDebug(new string('a', 10000)); + await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush + logger.LogDebug("tako"); + await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush + + File.Exists(path).Should().BeTrue(); + + loggerFactory.Dispose(); + + using (var fs = OpenFile(path1)) + { + fs.ReadLine().Should().Be("foo"); + fs.ReadLine().Should().Be("bar"); + fs.ReadLine().Should().Be("baz"); + fs.ReadLine().Should().BeNull(); + } + + using (var fs = OpenFile(path2)) + { + fs.ReadLine().Should().Be("a"); + fs.ReadLine().Should().Be("v"); + fs.ReadLine().Should().Be("c"); + } + } + } + } +} diff --git a/tests/ZLogger.Tests/ScopeTest.cs b/tests/ZLogger.Tests/ScopeTest.cs index 75d0192d..685f87b4 100644 --- a/tests/ZLogger.Tests/ScopeTest.cs +++ b/tests/ZLogger.Tests/ScopeTest.cs @@ -25,13 +25,10 @@ public ScopeTest() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => + x.AddZLoggerLogProcessor(options => { - zLogger.AddLogProcessor(options => - { - options.IncludeScopes = true; - return processor; - }); + options.IncludeScopes = true; + return processor; }); }); logger = loggerFactory.CreateLogger("test"); @@ -118,13 +115,10 @@ public void VersionMismatch() var invalidScopeStateOwner = new InvalidScopeStateOwner(); var loggerFactory = LoggerFactory.Create(x => { - x.AddZLogger(zLogger => + x.AddZLoggerLogProcessor(options => { - zLogger.AddLogProcessor(options => - { - options.IncludeScopes = true; - return invalidScopeStateOwner; - }); + options.IncludeScopes = true; + return invalidScopeStateOwner; }); }); logger = loggerFactory.CreateLogger("test"); diff --git a/tests/ZLogger.Tests/TimestampTest.cs b/tests/ZLogger.Tests/TimestampTest.cs index d1e24334..4d053079 100644 --- a/tests/ZLogger.Tests/TimestampTest.cs +++ b/tests/ZLogger.Tests/TimestampTest.cs @@ -27,19 +27,16 @@ string GetLogString(MessageTemplateHandler prefixTemplate) LogProcessor processor = new(); var factory = LoggerFactory.Create(builder => { - builder.AddZLogger(zlogger => + builder.AddZLoggerLogProcessor(options => { - zlogger.AddLogProcessor(options => + options.TimeProvider = new FakeTime(); + options.UsePlainTextFormatter(formatter => { - options.TimeProvider = new FakeTime(); - options.UsePlainTextFormatter(formatter => - { - formatter.SetPrefixFormatter(prefixTemplate, (template, info) => template.Format(info.Timestamp)); - }); - processor.SetOptions(options); - - return processor; + formatter.SetPrefixFormatter(prefixTemplate, (template, info) => template.Format(info.Timestamp)); }); + processor.SetOptions(options); + + return processor; }); }); From d04714849f668bddccdcf325a42f7f796bfd1b59 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:10:15 +0900 Subject: [PATCH 2/7] Rename fileName -> filePath --- .../Providers/ZLoggerRollingFileLoggerProvider.cs | 4 ++-- src/ZLogger/ZLoggerBuilder.cs | 13 ++++++------- tests/ZLogger.MessagePack.Tests/FormatterTest.cs | 1 - 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs b/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs index f29228d5..1891a5e3 100644 --- a/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs +++ b/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs @@ -19,10 +19,10 @@ public class ZLoggerRollingFileLoggerProvider : ILoggerProvider, ISupportExterna readonly AsyncStreamLineMessageWriter streamWriter; IExternalScopeProvider? scopeProvider; - public ZLoggerRollingFileLoggerProvider(Func fileNameSelector, RollingInterval rollInterval, int rollSizeKB, ZLoggerOptions options) + public ZLoggerRollingFileLoggerProvider(Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, ZLoggerOptions options) { this.options = options; - var stream = new RollingFileStream(fileNameSelector, rollInterval, rollSizeKB, options.TimeProvider); + var stream = new RollingFileStream(filePathSelector, rollInterval, rollSizeKB, options.TimeProvider); this.streamWriter = new AsyncStreamLineMessageWriter(stream, this.options); } diff --git a/src/ZLogger/ZLoggerBuilder.cs b/src/ZLogger/ZLoggerBuilder.cs index 61941318..54e1edcc 100644 --- a/src/ZLogger/ZLoggerBuilder.cs +++ b/src/ZLogger/ZLoggerBuilder.cs @@ -85,17 +85,16 @@ public static ILoggingBuilder AddZLoggerStream(this ILoggingBuilder builder, Fun return builder; } - // TODO: filePathにする - public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName) => builder.AddZLoggerFile((_, _) => fileName); - public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName, Action configure) => builder.AddZLoggerFile((o, _) => { configure(o); return fileName; }); - public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string fileName, Action configure) => builder.AddZLoggerFile((o, p) => { configure(o, p); return fileName; }); - public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, Func fileNameFactory) + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string filePath) => builder.AddZLoggerFile((_, _) => filePath); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string filePath, Action configure) => builder.AddZLoggerFile((o, _) => { configure(o); return filePath; }); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, string filePath, Action configure) => builder.AddZLoggerFile((o, p) => { configure(o, p); return filePath; }); + public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, Func filePathFactory) { builder.Services.AddSingleton(serviceProvider => { var options = new ZLoggerOptions(); - var fileName = fileNameFactory(options, serviceProvider); - return new ZLoggerFileLoggerProvider(fileName, options); + var filePath = filePathFactory(options, serviceProvider); + return new ZLoggerFileLoggerProvider(filePath, options); }); return builder; } diff --git a/tests/ZLogger.MessagePack.Tests/FormatterTest.cs b/tests/ZLogger.MessagePack.Tests/FormatterTest.cs index 306dcdbd..f1350965 100644 --- a/tests/ZLogger.MessagePack.Tests/FormatterTest.cs +++ b/tests/ZLogger.MessagePack.Tests/FormatterTest.cs @@ -1,6 +1,5 @@ using System; using FluentAssertions; -using MessagePack; using Microsoft.Extensions.Logging; using Xunit; From c812f8df4727bdbf64332afb26ed8e3733587465 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:21:18 +0900 Subject: [PATCH 3/7] Add InMemory builder overloads --- src/ZLogger/ZLoggerBuilder.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/ZLogger/ZLoggerBuilder.cs b/src/ZLogger/ZLoggerBuilder.cs index 54e1edcc..0077c953 100644 --- a/src/ZLogger/ZLoggerBuilder.cs +++ b/src/ZLogger/ZLoggerBuilder.cs @@ -35,9 +35,9 @@ public static ILoggingBuilder AddZLoggerConsole(this ILoggingBuilder builder, Ac return builder; } - // TODO:空のやつ追加!!Q!! - // TODO: ZloggerOptionsのやつだけ!! - public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configureProcessor) => AddZLoggerInMemory(null, (_, _) => { }, configureProcessor); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder) => builder.AddZLoggerInMemory(null, (_, _) => { }, _ => { }); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configureProcessor) => builder.AddZLoggerInMemory(null, (_, _) => { }, configureProcessor); + public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(null, configure, configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(null, configure, configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(processorKey, (o, _) => configure(o), configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) @@ -99,7 +99,6 @@ public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, Func< return builder; } - // TODO: optionsのやつ追加 /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files /// Limit size of single file. From c0fbdb4be932417f1a3a3845ca2ee4b29856f588 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:28:53 +0900 Subject: [PATCH 4/7] Fix test --- tests/ZLogger.Tests/FileProviderTest.cs | 4 +- tests/ZLogger.Tests/ProviderTest.cs | 150 ------------------ .../ZLogger.Tests/RollingFileProviderTest.cs | 8 +- 3 files changed, 6 insertions(+), 156 deletions(-) delete mode 100644 tests/ZLogger.Tests/ProviderTest.cs diff --git a/tests/ZLogger.Tests/FileProviderTest.cs b/tests/ZLogger.Tests/FileProviderTest.cs index 39858d8a..b003f4aa 100644 --- a/tests/ZLogger.Tests/FileProviderTest.cs +++ b/tests/ZLogger.Tests/FileProviderTest.cs @@ -15,7 +15,7 @@ public void CreateAppend() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddFile(Path)); + x.AddZLoggerFile(Path); }); var logger = loggerFactory.CreateLogger("mytest"); @@ -41,7 +41,7 @@ public void CreateAppend() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddFile(Path)); + x.AddZLoggerFile(Path); }); var logger = loggerFactory.CreateLogger("mytest"); diff --git a/tests/ZLogger.Tests/ProviderTest.cs b/tests/ZLogger.Tests/ProviderTest.cs deleted file mode 100644 index ff28e178..00000000 --- a/tests/ZLogger.Tests/ProviderTest.cs +++ /dev/null @@ -1,150 +0,0 @@ -using FluentAssertions; -using Microsoft.Extensions.Logging; -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using Xunit; - -namespace ZLogger.Tests -{ - public class ProviderTest - { - [Fact] - public void FileProvider() - { - const string Path = "ZLoggerTest.log"; - if (File.Exists(Path)) File.Delete(Path); - { - var loggerFactory = LoggerFactory.Create(x => - { - x.SetMinimumLevel(LogLevel.Debug); - x.AddZLoggerFile(Path); - }); - - var logger = loggerFactory.CreateLogger("mytest"); - - logger.LogDebug("foo"); - logger.LogDebug("bar"); - logger.LogDebug("baz"); - - loggerFactory.Dispose(); - - using (var fs = File.OpenText(Path)) - { - fs.ReadLine().Should().Be("foo"); - fs.ReadLine().Should().Be("bar"); - fs.ReadLine().Should().Be("baz"); - fs.ReadLine().Should().BeNull(); - } - } - - { - // append check - - var loggerFactory = LoggerFactory.Create(x => - { - x.SetMinimumLevel(LogLevel.Debug); - x.AddZLoggerFile(Path); - }); - - var logger = loggerFactory.CreateLogger("mytest"); - - logger.LogDebug("abc"); - logger.LogDebug("def"); - logger.LogDebug("ghi"); - - loggerFactory.Dispose(); - - using (var fs = File.OpenText(Path)) - { - fs.ReadLine().Should().Be("foo"); - fs.ReadLine().Should().Be("bar"); - fs.ReadLine().Should().Be("baz"); - fs.ReadLine().Should().Be("abc"); - fs.ReadLine().Should().Be("def"); - fs.ReadLine().Should().Be("ghi"); - fs.ReadLine().Should().BeNull(); - } - } - - } - - static StreamReader OpenFile(string path) - { - return new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); - } - - [Fact] - public async Task RollingFileProvider() - { - { - var now = new DateTime(2000, 12, 12); - - var path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-0.log"; - if (File.Exists(path)) File.Delete(path); - - var loggerFactory = LoggerFactory.Create(x => - { - x.SetMinimumLevel(LogLevel.Debug); - x.AddZLoggerRollingFile( - (dt, seq) => $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-{seq}.log", - x => now, 5); - }); - - var logger = loggerFactory.CreateLogger("mytest"); - - logger.LogDebug("foo"); - logger.LogDebug("bar"); - logger.LogDebug("baz"); - - await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush - - File.Exists(path).Should().BeTrue(); - var path1 = path; - - // roll next file - now = now.AddDays(1); - path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-0.log"; - if (File.Exists(path)) File.Delete(path); - - logger.LogDebug("a"); - logger.LogDebug("v"); - logger.LogDebug("c"); - - await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush - - File.Exists(path).Should().BeTrue(); - var path2 = path; - - // roll by filesize - path = $"ZLoggerRollingTest_{now.Date.ToString("yyyy-MM-dd")}-1.log"; - if (File.Exists(path)) File.Delete(path); - - logger.LogDebug(new string('a', 10000)); - await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush - logger.LogDebug("tako"); - await Task.Delay(TimeSpan.FromSeconds(1)); // wait for flush - - File.Exists(path).Should().BeTrue(); - - loggerFactory.Dispose(); - - using (var fs = OpenFile(path1)) - { - fs.ReadLine().Should().Be("foo"); - fs.ReadLine().Should().Be("bar"); - fs.ReadLine().Should().Be("baz"); - fs.ReadLine().Should().BeNull(); - } - - using (var fs = OpenFile(path2)) - { - fs.ReadLine().Should().Be("a"); - fs.ReadLine().Should().Be("v"); - fs.ReadLine().Should().Be("c"); - } - } - } - } -} diff --git a/tests/ZLogger.Tests/RollingFileProviderTest.cs b/tests/ZLogger.Tests/RollingFileProviderTest.cs index 10b8c13b..68a1d18d 100644 --- a/tests/ZLogger.Tests/RollingFileProviderTest.cs +++ b/tests/ZLogger.Tests/RollingFileProviderTest.cs @@ -36,11 +36,11 @@ public async Task RollByInterval() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddRollingFile( + x.AddZLoggerRollingFile( (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"), RollingInterval.Day, 5, - options => options.TimeProvider = timeProvider)); + options => options.TimeProvider = timeProvider); }); File.Exists(path1).Should().Be(true); @@ -93,11 +93,11 @@ public async Task RollBySize() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLogger(zLogger => zLogger.AddRollingFile( + x.AddZLoggerRollingFile( (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"), RollingInterval.Day, 5, - options => options.TimeProvider = timeProvider)); + options => options.TimeProvider = timeProvider); }); File.Exists(path1).Should().Be(true); From 0c69eecda6791823aa7f30f82730550a8d425542 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:41:52 +0900 Subject: [PATCH 5/7] Add ZLoggerRollingFileOptions --- .../ZLoggerRollingFileLoggerProvider.cs | 17 +++++-- src/ZLogger/ZLoggerBuilder.cs | 44 ++++++++++++++----- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs b/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs index 1891a5e3..024c1cf4 100644 --- a/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs +++ b/src/ZLogger/Providers/ZLoggerRollingFileLoggerProvider.cs @@ -12,17 +12,28 @@ public enum RollingInterval Minute } +public sealed class ZLoggerRollingFileOptions : ZLoggerOptions +{ + public Func? FilePathSelector { get; set; } + public RollingInterval RollingInterval { get; set; } = RollingInterval.Day; + public int RollingSizeKB { get; set; } = 512 * 1024; +} + [ProviderAlias("ZLoggerRollingFile")] public class ZLoggerRollingFileLoggerProvider : ILoggerProvider, ISupportExternalScope, IAsyncDisposable { - readonly ZLoggerOptions options; + readonly ZLoggerRollingFileOptions options; readonly AsyncStreamLineMessageWriter streamWriter; IExternalScopeProvider? scopeProvider; - public ZLoggerRollingFileLoggerProvider(Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, ZLoggerOptions options) + public ZLoggerRollingFileLoggerProvider(ZLoggerRollingFileOptions options) { + if (options.FilePathSelector is null) + { + throw new ArgumentException(nameof(options.FilePathSelector)); + } this.options = options; - var stream = new RollingFileStream(filePathSelector, rollInterval, rollSizeKB, options.TimeProvider); + var stream = new RollingFileStream(options.FilePathSelector!, options.RollingInterval, options.RollingSizeKB, options.TimeProvider); this.streamWriter = new AsyncStreamLineMessageWriter(stream, this.options); } diff --git a/src/ZLogger/ZLoggerBuilder.cs b/src/ZLogger/ZLoggerBuilder.cs index 0077c953..829773c4 100644 --- a/src/ZLogger/ZLoggerBuilder.cs +++ b/src/ZLogger/ZLoggerBuilder.cs @@ -98,31 +98,51 @@ public static ILoggingBuilder AddZLoggerFile(this ILoggingBuilder builder, Func< }); return builder; } - + /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files - /// Limit size of single file. - public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB) => - builder.AddZLoggerRollingFile(filePathSelector, rollInterval, rollSizeKB, (_, _) => { }); + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval) => + builder.AddZLoggerRollingFile((o, _) => + { + o.FilePathSelector = filePathSelector; + o.RollingInterval = rollInterval; + o.RollingSizeKB = int.MaxValue; + }); + /// DateTimeOffset is date of file open time(UTC), int is number sequence. - /// Interval to automatically rotate files /// Limit size of single file. - public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) => - builder.AddZLoggerRollingFile(filePathSelector, rollInterval, rollSizeKB, (o, _) => configure(o)); - + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, int rollSizeKB) => + builder.AddZLoggerRollingFile((o, _) => + { + o.FilePathSelector = filePathSelector; + o.RollingInterval = RollingInterval.Infinite; + o.RollingSizeKB = rollSizeKB; + }); + /// DateTimeOffset is date of file open time(UTC), int is number sequence. /// Interval to automatically rotate files /// Limit size of single file. - public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB, Action configure) + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Func filePathSelector, RollingInterval rollInterval, int rollSizeKB) => + builder.AddZLoggerRollingFile((o, _) => + { + o.FilePathSelector = filePathSelector; + o.RollingInterval = rollInterval; + o.RollingSizeKB = rollSizeKB; + }); + + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Action configure) => + builder.AddZLoggerRollingFile((o, _) => configure(o)); + + public static ILoggingBuilder AddZLoggerRollingFile(this ILoggingBuilder builder, Action configure) { builder.Services.AddSingleton(serviceProvider => { - var options = new ZLoggerOptions(); + var options = new ZLoggerRollingFileOptions(); configure(options, serviceProvider); - return new ZLoggerRollingFileLoggerProvider(filePathSelector, rollInterval, rollSizeKB, options); + return new ZLoggerRollingFileLoggerProvider(options); }); return builder; } - } + From 34074337f659ee81dd3fb3db1e6e6152a06a8837 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 18:59:12 +0900 Subject: [PATCH 6/7] Removed overloads that confuse Intellisense. --- src/ZLogger/ZLoggerBuilder.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ZLogger/ZLoggerBuilder.cs b/src/ZLogger/ZLoggerBuilder.cs index 829773c4..6f36e1d2 100644 --- a/src/ZLogger/ZLoggerBuilder.cs +++ b/src/ZLogger/ZLoggerBuilder.cs @@ -37,7 +37,6 @@ public static ILoggingBuilder AddZLoggerConsole(this ILoggingBuilder builder, Ac public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder) => builder.AddZLoggerInMemory(null, (_, _) => { }, _ => { }); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configureProcessor) => builder.AddZLoggerInMemory(null, (_, _) => { }, configureProcessor); - public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(null, configure, configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(null, configure, configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) => builder.AddZLoggerInMemory(processorKey, (o, _) => configure(o), configureProcessor); public static ILoggingBuilder AddZLoggerInMemory(this ILoggingBuilder builder, object? processorKey, Action configure, Action configureProcessor) From 6dd095bba12c0af74b04b89580b94103da68cc73 Mon Sep 17 00:00:00 2001 From: hadashiA Date: Fri, 1 Dec 2023 19:02:33 +0900 Subject: [PATCH 7/7] Fix compilation errors --- .../ZLogger.Tests/RollingFileProviderTest.cs | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/tests/ZLogger.Tests/RollingFileProviderTest.cs b/tests/ZLogger.Tests/RollingFileProviderTest.cs index 68a1d18d..9919a11a 100644 --- a/tests/ZLogger.Tests/RollingFileProviderTest.cs +++ b/tests/ZLogger.Tests/RollingFileProviderTest.cs @@ -36,11 +36,13 @@ public async Task RollByInterval() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLoggerRollingFile( - (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"), - RollingInterval.Day, - 5, - options => options.TimeProvider = timeProvider); + x.AddZLoggerRollingFile(options => + { + options.FilePathSelector = (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"); + options.RollingInterval = RollingInterval.Day; + options.RollingSizeKB = 5; + options.TimeProvider = timeProvider; + }); }); File.Exists(path1).Should().Be(true); @@ -93,11 +95,13 @@ public async Task RollBySize() var loggerFactory = LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Debug); - x.AddZLoggerRollingFile( - (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"), - RollingInterval.Day, - 5, - options => options.TimeProvider = timeProvider); + x.AddZLoggerRollingFile(options => + { + options.FilePathSelector = (dt, seq) => Path.Join(directory, $"ZLoggerRollingTest_{dt:yyyy-MM-dd}-{seq}.log"); + options.RollingInterval = RollingInterval.Day; + options.RollingSizeKB = 5; + options.TimeProvider = timeProvider; + }); }); File.Exists(path1).Should().Be(true);