diff --git a/samples/SimpleServiceSample/Program.cs b/samples/SimpleServiceSample/Program.cs index bd21ea5..8cbf6bd 100644 --- a/samples/SimpleServiceSample/Program.cs +++ b/samples/SimpleServiceSample/Program.cs @@ -1,9 +1,9 @@ -using System; -using System.IO; -using Microsoft.Extensions.Configuration; +using Cnblogs.Serilog.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Serilog; +using System; namespace SimpleServiceSample { @@ -36,9 +36,10 @@ public static int Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(services => services.AddHostedService()) - .UseSerilog((context, services, loggerConfiguration) => loggerConfiguration - .ReadFrom.Configuration(context.Configuration) + .ConfigureLogging((context, logging) => + logging.AddSerilog((conf, loggerConfiguration) => loggerConfiguration + .ReadFrom.Configuration(conf) .Enrich.FromLogContext() - .WriteTo.Console()); + .WriteTo.Console())); } -} +} \ No newline at end of file diff --git a/samples/WebApplicationSample/Program.cs b/samples/WebApplicationSample/Program.cs index 3fcae13..b95866d 100644 --- a/samples/WebApplicationSample/Program.cs +++ b/samples/WebApplicationSample/Program.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Cnblogs.Serilog.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; @@ -17,7 +18,7 @@ public static int Main(string[] args) Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateBootstrapLogger(); - + Log.Information("Starting up!"); try @@ -40,10 +41,11 @@ public static int Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .UseSerilog((context, services, configuration) => configuration + .ConfigureLogging((context, logging) => + logging.AddSerilogFactory((services, loggerConfig) => loggerConfig .WriteTo.Console() .ReadFrom.Configuration(context.Configuration) - .ReadFrom.Services(services)) + .ReadFrom.Services(services))) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } } \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/AmbientDiagnosticContextCollector.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/AmbientDiagnosticContextCollector.cs index 68010ee..fdc0b2b 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/AmbientDiagnosticContextCollector.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/AmbientDiagnosticContextCollector.cs @@ -15,7 +15,7 @@ using System; using System.Threading; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { class AmbientDiagnosticContextCollector : IDisposable { diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/CachingReloadableLogger.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/CachingReloadableLogger.cs index 3a8fee6..a072520 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/CachingReloadableLogger.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/CachingReloadableLogger.cs @@ -17,17 +17,18 @@ using System; using System.Collections.Generic; using System.Threading; +using Serilog; using Serilog.Core; using Serilog.Events; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { class CachingReloadableLogger : ILogger, IReloadableLogger { readonly ReloadableLogger _reloadableLogger; readonly Func _configure; readonly IReloadableLogger _parent; - + ILogger _root, _cached; bool _frozen; @@ -49,14 +50,14 @@ public ILogger ReloadLogger() public ILogger ForContext(ILogEventEnricher enricher) { if (enricher == null) return this; - + if (_frozen) return _cached.ForContext(enricher); if (_reloadableLogger.CreateChild( _root, this, - _cached, + _cached, p => p.ForContext(enricher), out var child, out var newRoot, @@ -72,14 +73,14 @@ public ILogger ForContext(ILogEventEnricher enricher) public ILogger ForContext(IEnumerable enrichers) { if (enrichers == null) return this; - + if (_frozen) return _cached.ForContext(enrichers); if (_reloadableLogger.CreateChild( _root, this, - _cached, + _cached, p => p.ForContext(enrichers), out var child, out var newRoot, @@ -95,7 +96,7 @@ public ILogger ForContext(IEnumerable enrichers) public ILogger ForContext(string propertyName, object value, bool destructureObjects = false) { if (propertyName == null) return this; - + if (_frozen) return _cached.ForContext(propertyName, value, destructureObjects); @@ -126,7 +127,7 @@ public ILogger ForContext(string propertyName, object value, bool destructureObj return this; var enricher = new FixedPropertyEnricher(property); - + if (_reloadableLogger.CreateChild( _root, this, @@ -148,11 +149,11 @@ public ILogger ForContext() { if (_frozen) return _cached.ForContext(); - + if (_reloadableLogger.CreateChild( _root, this, - _cached, + _cached, p => p.ForContext(), out var child, out var newRoot, @@ -173,7 +174,7 @@ public ILogger ForContext(Type source) if (_reloadableLogger.CreateChild( _root, this, - _cached, + _cached, p => p.ForContext(source), out var child, out var newRoot, @@ -190,7 +191,7 @@ void Update(ILogger newRoot, ILogger newCached, bool frozen) { _root = newRoot; _cached = newCached; - + // https://github.com/dotnet/runtime/issues/20500#issuecomment-284774431 // Publish `_cached` and then `_frozen`. This is useful here because it means that once the logger is frozen - which // we always expect - reads don't require any synchronization/interlocked instructions. @@ -486,7 +487,7 @@ public bool IsEnabled(LogEventLevel level) return isEnabled; } - + public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, out IEnumerable boundProperties) { @@ -542,4 +543,4 @@ public bool BindProperty(string propertyName, object value, bool destructureObje } } -#endif +#endif \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContext.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContext.cs index 44462ac..f0a56ef 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContext.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContext.cs @@ -12,10 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Serilog; using System; using System.Threading; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { /// /// Implements an ambient diagnostic context using . @@ -23,7 +24,7 @@ namespace Serilog.Extensions.Hosting /// Consumers should use to set context properties. public sealed class DiagnosticContext : IDiagnosticContext { - readonly ILogger _logger; + private readonly ILogger _logger; /// /// Construct a . @@ -50,7 +51,7 @@ public void Set(string propertyName, object value, bool destructureObjects = fal if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); var collector = AmbientDiagnosticContextCollector.Current; - if (collector != null && + if (collector != null && (_logger ?? Log.Logger).BindProperty(propertyName, value, destructureObjects, out var property)) { collector.AddOrUpdate(property); @@ -64,4 +65,4 @@ public void SetException(Exception exception) collector?.SetException(exception); } } -} +} \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContextCollector.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContextCollector.cs index 63c6339..f2678b2 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContextCollector.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/DiagnosticContextCollector.cs @@ -2,17 +2,17 @@ using System.Collections.Generic; using Serilog.Events; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { /// /// A container that receives properties added to a diagnostic context. /// public sealed class DiagnosticContextCollector : IDisposable { - readonly IDisposable _chainedDisposable; - readonly object _propertiesLock = new object(); - Exception _exception; - Dictionary _properties = new Dictionary(); + private readonly IDisposable _chainedDisposable; + private readonly object _propertiesLock = new object(); + private Exception _exception; + private Dictionary _properties = new Dictionary(); /// /// Construct a . @@ -84,7 +84,7 @@ public bool TryComplete(out IEnumerable properties) /// The collected exception, or null if none has been collected or if no collection is active. /// True if properties could be collected. /// - /// + /// public bool TryComplete(out IEnumerable properties, out Exception exception) { lock (_propertiesLock) @@ -104,4 +104,4 @@ public void Dispose() _chainedDisposable.Dispose(); } } -} +} \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/FixedPropertyEnricher.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/FixedPropertyEnricher.cs index 3543173..02f5566 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/FixedPropertyEnricher.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/FixedPropertyEnricher.cs @@ -15,7 +15,7 @@ using Serilog.Core; using Serilog.Events; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { class FixedPropertyEnricher : ILogEventEnricher { diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/IReloadableLogger.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/IReloadableLogger.cs index 07b4cf9..7d1254b 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/IReloadableLogger.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/IReloadableLogger.cs @@ -12,9 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Serilog.Extensions.Hosting +using Serilog; + +namespace Cnblogs.Serilog.Extensions { - interface IReloadableLogger + internal interface IReloadableLogger { ILogger ReloadLogger(); } diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/InjectedLoggerSettings.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/InjectedLoggerSettings.cs index 97e37ea..6b1ca8c 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/InjectedLoggerSettings.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/InjectedLoggerSettings.cs @@ -1,13 +1,14 @@ using System; using Microsoft.Extensions.DependencyInjection; +using Serilog; using Serilog.Configuration; using Serilog.Core; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { - class InjectedLoggerSettings : ILoggerSettings + internal class InjectedLoggerSettings : ILoggerSettings { - readonly IServiceProvider _services; + private readonly IServiceProvider _services; public InjectedLoggerSettings(IServiceProvider services) { @@ -19,7 +20,7 @@ public void Configure(LoggerConfiguration loggerConfiguration) var levelSwitch = _services.GetService(); if (levelSwitch != null) loggerConfiguration.MinimumLevel.ControlledBy(levelSwitch); - + foreach (var settings in _services.GetServices()) loggerConfiguration.ReadFrom.Settings(settings); @@ -28,12 +29,12 @@ public void Configure(LoggerConfiguration loggerConfiguration) foreach (var enricher in _services.GetServices()) loggerConfiguration.Enrich.With(enricher); - + foreach (var filter in _services.GetServices()) loggerConfiguration.Filter.With(filter); - + foreach (var sink in _services.GetServices()) loggerConfiguration.WriteTo.Sink(sink); } } -} +} \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/NullEnricher.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/NullEnricher.cs index af13dfc..ab294bb 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/NullEnricher.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/NullEnricher.cs @@ -15,7 +15,7 @@ using Serilog.Core; using Serilog.Events; -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { // Does nothing, but makes it easy to create an `ILogger` from a Serilog `Logger` // that will not dispose the underlying pipeline when disposed itself. diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/ReloadableLogger.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/ReloadableLogger.cs index 6ec1d37..cb4c350 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/ReloadableLogger.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/ReloadableLogger.cs @@ -14,16 +14,17 @@ #if !NO_RELOADABLE_LOGGER +using Serilog; +using Serilog.Core; +using Serilog.Events; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; -using Serilog.Core; -using Serilog.Events; // ReSharper disable MemberCanBePrivate.Global -namespace Serilog.Extensions.Hosting +namespace Cnblogs.Serilog.Extensions { /// /// A Serilog that can be reconfigured without invalidating existing @@ -33,7 +34,7 @@ public sealed class ReloadableLogger : ILogger, IReloadableLogger, IDisposable { readonly object _sync = new object(); Logger _logger; - + // One-way; if the value is `true` it can never again be made `false`, allowing "double-checked" reads. If // `true`, `_logger` is final and a memory barrier ensures the final value is seen by all threads. bool _frozen; @@ -43,7 +44,7 @@ internal ReloadableLogger(Logger initial) { _logger = initial ?? throw new ArgumentNullException(nameof(initial)); } - + ILogger IReloadableLogger.ReloadLogger() { return _logger; @@ -57,7 +58,7 @@ ILogger IReloadableLogger.ReloadLogger() public void Reload(Func configure) { if (configure == null) throw new ArgumentNullException(nameof(configure)); - + lock (_sync) { _logger.Dispose(); @@ -85,7 +86,7 @@ public Logger Freeze() // Publish `_logger` and `_frozen`. This is useful here because it means that once the logger is frozen - which // we always expect - reads don't require any synchronization/interlocked instructions. Interlocked.MemoryBarrierProcessWide(); - + return _logger; } } @@ -101,7 +102,7 @@ public void Dispose() public ILogger ForContext(ILogEventEnricher enricher) { if (enricher == null) return this; - + if (_frozen) return _logger.ForContext(enricher); @@ -113,7 +114,7 @@ public ILogger ForContext(ILogEventEnricher enricher) public ILogger ForContext(IEnumerable enrichers) { if (enrichers == null) return this; - + if (_frozen) return _logger.ForContext(enrichers); @@ -125,7 +126,7 @@ public ILogger ForContext(IEnumerable enrichers) public ILogger ForContext(string propertyName, object value, bool destructureObjects = false) { if (propertyName == null) return this; - + if (_frozen) return _logger.ForContext(propertyName, value, destructureObjects); @@ -147,7 +148,7 @@ public ILogger ForContext() public ILogger ForContext(Type source) { if (source == null) return this; - + if (_frozen) return _logger.ForContext(source); @@ -335,7 +336,7 @@ public bool IsEnabled(LogEventLevel level) return _logger.IsEnabled(level); } } - + /// public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, out IEnumerable boundProperties) @@ -370,7 +371,7 @@ public bool BindProperty(string propertyName, object value, bool destructureObje { // Synchronization on `_sync` is not required in this method; it will be called without a lock // if `_frozen` and under a lock if not. - + if (_frozen) { // If we're frozen, then the caller hasn't observed this yet and should update. We could optimize a little here @@ -388,13 +389,13 @@ public bool BindProperty(string propertyName, object value, bool destructureObje frozen = false; return (cached, false); } - + newRoot = _logger; newCached = caller.ReloadLogger(); frozen = false; return (newCached, true); } - + internal bool InvokeIsEnabled(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, out bool isEnabled, out ILogger newRoot, out ILogger newCached, out bool frozen) { if (_frozen) @@ -411,8 +412,8 @@ internal bool InvokeIsEnabled(ILogger root, ILogger cached, IReloadableLogger ca return update; } } - - internal bool InvokeBindMessageTemplate(ILogger root, ILogger cached, IReloadableLogger caller, string messageTemplate, + + internal bool InvokeBindMessageTemplate(ILogger root, ILogger cached, IReloadableLogger caller, string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, out IEnumerable boundProperties, out bool canBind, out ILogger newRoot, out ILogger newCached, out bool frozen) { @@ -430,8 +431,8 @@ internal bool InvokeBindMessageTemplate(ILogger root, ILogger cached, IReloadabl return update; } } - - internal bool InvokeBindProperty(ILogger root, ILogger cached, IReloadableLogger caller, string propertyName, + + internal bool InvokeBindProperty(ILogger root, ILogger cached, IReloadableLogger caller, string propertyName, object propertyValue, bool destructureObjects, out LogEventProperty property, out bool canBind, out ILogger newRoot, out ILogger newCached, out bool frozen) { @@ -503,7 +504,7 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger cal return update; } } - + internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, out ILogger newRoot, out ILogger newCached, out bool frozen) @@ -522,7 +523,7 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogge return update; } } - + internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2, out ILogger newRoot, out ILogger newCached, out bool frozen) @@ -560,7 +561,7 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller return update; } } - + internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, Exception exception, string messageTemplate, out ILogger newRoot, out ILogger newCached, out bool frozen) { @@ -597,7 +598,7 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger cal return update; } } - + internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, out ILogger newRoot, out ILogger newCached, out bool frozen) @@ -616,7 +617,7 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogge return update; } } - + internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller, LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2, out ILogger newRoot, out ILogger newCached, out bool frozen) @@ -656,8 +657,8 @@ internal bool InvokeWrite(ILogger root, ILogger cached, IReloadableLogger caller } internal bool CreateChild( - ILogger root, - IReloadableLogger parent, + ILogger root, + IReloadableLogger parent, ILogger cachedParent, Func configureChild, out ILogger child, @@ -683,4 +684,4 @@ internal bool CreateChild( } } -#endif +#endif \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/Extensions/Hosting/SerilogLoggerFactory.cs b/src/Serilog.Extensions.Hosting/Extensions/Hosting/SerilogLoggerFactory.cs index 1b100b9..703ad05 100644 --- a/src/Serilog.Extensions.Hosting/Extensions/Hosting/SerilogLoggerFactory.cs +++ b/src/Serilog.Extensions.Hosting/Extensions/Hosting/SerilogLoggerFactory.cs @@ -12,16 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using System.ComponentModel; -using Microsoft.Extensions.Logging; +using Serilog; using Serilog.Debugging; using Serilog.Extensions.Logging; +using System; +using System.ComponentModel; +using ILoggerFactory = Microsoft.Extensions.Logging.ILoggerFactory; // To line up with the convention used elsewhere in the *.Extensions libraries, this // should have been Serilog.Extensions.Hosting. // ReSharper disable once CheckNamespace -namespace Serilog.Hosting +namespace Cnblogs.Serilog.Extensions.Hosting { /// /// Implements so that we can inject Serilog Logger. @@ -30,12 +31,12 @@ namespace Serilog.Hosting [EditorBrowsable(EditorBrowsableState.Never)] public class SerilogLoggerFactory : ILoggerFactory { - readonly SerilogLoggerProvider _provider; + private readonly SerilogLoggerProvider _provider; /// /// Initializes a new instance of the class. /// - /// The Serilog logger; if not supplied, the static will be used. + /// The Serilog logger; if not supplied, the static will be used. /// When true, dispose when the framework disposes the provider. If the /// logger is not specified but is true, the method will be /// called on the static class instead. @@ -68,9 +69,9 @@ public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) /// Adds an to the logging system. /// /// The . - public void AddProvider(ILoggerProvider provider) + public void AddProvider(Microsoft.Extensions.Logging.ILoggerProvider provider) { SelfLog.WriteLine("Ignoring add logger provider {0}", provider); } } -} +} \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/IDiagnosticContext.cs b/src/Serilog.Extensions.Hosting/IDiagnosticContext.cs index 79da237..56739ee 100644 --- a/src/Serilog.Extensions.Hosting/IDiagnosticContext.cs +++ b/src/Serilog.Extensions.Hosting/IDiagnosticContext.cs @@ -14,7 +14,8 @@ using System; -namespace Serilog +namespace + Cnblogs.Serilog.Extensions { /// /// Collects diagnostic information for packaging into wide events. diff --git a/src/Serilog.Extensions.Hosting/LoggerConfigurationExtensions.cs b/src/Serilog.Extensions.Hosting/LoggerConfigurationExtensions.cs index 51a02d1..57d5d43 100644 --- a/src/Serilog.Extensions.Hosting/LoggerConfigurationExtensions.cs +++ b/src/Serilog.Extensions.Hosting/LoggerConfigurationExtensions.cs @@ -14,11 +14,9 @@ #if !NO_RELOADABLE_LOGGER -using Microsoft.Extensions.Hosting; -using Serilog.Extensions.Hosting; -using System; +using Serilog; -namespace Serilog +namespace Cnblogs.Serilog.Extensions { /// /// Extends . @@ -27,7 +25,6 @@ public static class LoggerConfigurationExtensions { /// /// Create a for use during host bootstrapping. The - /// /// configuration overload will detect when is set to a instance, and /// reconfigure/freeze it so that s created during host bootstrapping continue to work once /// logger configuration (with access to host services) is completed. @@ -41,4 +38,4 @@ public static ReloadableLogger CreateBootstrapLogger(this LoggerConfiguration lo } } -#endif +#endif \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/LoggerSettingsConfigurationExtensions.cs b/src/Serilog.Extensions.Hosting/LoggerSettingsConfigurationExtensions.cs index 4e9c62c..40d14d4 100644 --- a/src/Serilog.Extensions.Hosting/LoggerSettingsConfigurationExtensions.cs +++ b/src/Serilog.Extensions.Hosting/LoggerSettingsConfigurationExtensions.cs @@ -13,11 +13,11 @@ // limitations under the License. using System; +using Serilog; using Serilog.Configuration; using Serilog.Core; -using Serilog.Extensions.Hosting; -namespace Serilog +namespace Cnblogs.Serilog.Extensions { /// /// Extends with methods for consuming host services. diff --git a/src/Serilog.Extensions.Hosting/Serilog.Extensions.Hosting.csproj b/src/Serilog.Extensions.Hosting/Serilog.Extensions.Hosting.csproj index cbf79ce..cbe6abd 100644 --- a/src/Serilog.Extensions.Hosting/Serilog.Extensions.Hosting.csproj +++ b/src/Serilog.Extensions.Hosting/Serilog.Extensions.Hosting.csproj @@ -8,17 +8,15 @@ true true Cnblogs.Serilog.Extensions - ../../assets/Serilog.snk true - true Cnblogs.Serilog.Extensions - serilog + serilog;logging https://github.com/cnblogs/cnblogs-serilog-extensions Apache-2.0 https://github.com/cnblogs/cnblogs-serilog-extensions git false - Serilog + Cnblogs.Serilog.Extensions diff --git a/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs b/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs deleted file mode 100644 index 2a66cdd..0000000 --- a/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2020 Serilog Contributors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Serilog.Extensions.Hosting; -using Serilog.Extensions.Logging; - -// ReSharper disable MemberCanBePrivate.Global - -namespace Serilog -{ - /// - /// Extends with Serilog configuration methods. - /// - public static class SerilogHostBuilderExtensions - { - // Used internally to pass information through the container. We need to do this because if `logger` is the - // root logger, registering it as a singleton may lead to disposal along with the container by MEDI. This isn't - // always desirable, i.e. we may be handed a logger and `dispose: false`, so wrapping it keeps us in control - // of when the logger is disposed. - internal class RegisteredLogger - { - public RegisteredLogger(ILogger logger) - { - Logger = logger; - } - - public ILogger Logger { get; } - } - - /// - /// Sets Serilog as the logging provider. - /// - /// The host builder to configure. - /// The Serilog logger; if not supplied, the static will be used. - /// When true, dispose when the framework disposes the provider. If the - /// logger is not specified but is true, the method will be - /// called on the static class instead. - /// A registered in the Serilog pipeline using the - /// WriteTo.Providers() configuration method, enabling other s to receive events. By - /// default, only Serilog sinks will receive events. - /// The host builder. - public static IHostBuilder UseSerilog( - this IHostBuilder builder, - ILogger logger = null, - bool dispose = false, - LoggerProviderCollection providers = null) - { - return builder.ConfigureServices((context, services) => - services.AddLogging(logging => logging.AddSerilog(logger, dispose, providers))); - } - - /// Sets Serilog as the logging provider. - /// - /// A is supplied so that configuration and hosting information can be used. - /// The logger will be shut down when application services are disposed. - /// - /// The host builder to configure. - /// The delegate for configuring the that will be used to construct a . - /// Indicates whether to preserve the value of . - /// By default, Serilog does not write events to s registered through - /// the Microsoft.Extensions.Logging API. Normally, equivalent Serilog sinks are used in place of providers. Specify - /// true to write events to all providers. - /// The host builder. - public static IHostBuilder UseSerilog( - this IHostBuilder builder, - Action configureLogger, - bool preserveStaticLogger = false, - bool writeToProviders = false) - { - if (builder == null) throw new ArgumentNullException(nameof(builder)); - if (configureLogger == null) throw new ArgumentNullException(nameof(configureLogger)); - return UseSerilog( - builder, - (hostBuilderContext, services, loggerConfiguration) => - configureLogger(hostBuilderContext, loggerConfiguration), - preserveStaticLogger: preserveStaticLogger, - writeToProviders: writeToProviders); - } - - /// Sets Serilog as the logging provider. - /// - /// A is supplied so that configuration and hosting information can be used. - /// The logger will be shut down when application services are disposed. - /// - /// The host builder to configure. - /// The delegate for configuring the that will be used to construct a . - /// Indicates whether to preserve the value of . - /// By default, Serilog does not write events to s registered through - /// the Microsoft.Extensions.Logging API. Normally, equivalent Serilog sinks are used in place of providers. Specify - /// true to write events to all providers. - /// If the static is a bootstrap logger (see - /// LoggerConfigurationExtensions.CreateBootstrapLogger()), and is - /// not specified, the the bootstrap logger will be reconfigured through the supplied delegate, rather than being - /// replaced entirely or ignored. - /// The host builder. - public static IHostBuilder UseSerilog( - this IHostBuilder builder, - Action configureLogger, - bool preserveStaticLogger = false, - bool writeToProviders = false) - { - if (builder == null) throw new ArgumentNullException(nameof(builder)); - if (configureLogger == null) throw new ArgumentNullException(nameof(configureLogger)); - - // This check is eager; replacing the bootstrap logger after calling this method is not supported. -#if !NO_RELOADABLE_LOGGER - var reloadable = Log.Logger as ReloadableLogger; - var useReload = reloadable != null && !preserveStaticLogger; -#else - const bool useReload = false; -#endif - - builder.ConfigureServices((context, collection) => - { - LoggerProviderCollection loggerProviders = null; - if (writeToProviders) - { - loggerProviders = new LoggerProviderCollection(); - } - - collection.AddSingleton(services => - { - ILogger logger; -#if !NO_RELOADABLE_LOGGER - if (useReload) - { - reloadable!.Reload(cfg => - { - if (loggerProviders != null) - cfg.WriteTo.Providers(loggerProviders); - - configureLogger(context, services, cfg); - return cfg; - }); - - logger = reloadable.Freeze(); - } - else -#endif - { - var loggerConfiguration = new LoggerConfiguration(); - - if (loggerProviders != null) - loggerConfiguration.WriteTo.Providers(loggerProviders); - - configureLogger(context, services, loggerConfiguration); - logger = loggerConfiguration.CreateLogger(); - } - - return new RegisteredLogger(logger); - }); - - collection.AddSingleton(services => - { - // How can we register the logger, here, but not have MEDI dispose it? - // Using the `NullEnricher` hack to prevent disposal. - var logger = services.GetRequiredService().Logger; - return logger.ForContext(new NullEnricher()); - }); - - collection.AddSingleton(services => - { - var logger = services.GetRequiredService().Logger; - - ILogger registeredLogger = null; - if (preserveStaticLogger) - { - registeredLogger = logger; - } - else - { - // Passing a `null` logger to `SerilogLoggerFactory` results in disposal via - // `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op. - Log.Logger = logger; - } - - var factory = new SerilogLoggerFactory(registeredLogger, !useReload, loggerProviders); - - if (writeToProviders) - { - foreach (var provider in services.GetServices()) - factory.AddProvider(provider); - } - - return factory; - }); - - ConfigureDiagnosticContext(collection, preserveStaticLogger); - }); - - return builder; - } - - internal static void ConfigureDiagnosticContext(IServiceCollection collection, bool useRegisteredLogger) - { - if (collection == null) throw new ArgumentNullException(nameof(collection)); - - // Registered to provide two services... - // Consumed by e.g. middleware - collection.AddSingleton(services => - { - ILogger logger = useRegisteredLogger ? services.GetRequiredService().Logger : null; - return new DiagnosticContext(logger); - }); - // Consumed by user code - collection.AddSingleton(services => services.GetRequiredService()); - } - } -} \ No newline at end of file diff --git a/src/Serilog.Extensions.Hosting/SerilogLoggingBuilderExtensions.cs b/src/Serilog.Extensions.Hosting/SerilogLoggingBuilderExtensions.cs index 4efc041..aa171a6 100644 --- a/src/Serilog.Extensions.Hosting/SerilogLoggingBuilderExtensions.cs +++ b/src/Serilog.Extensions.Hosting/SerilogLoggingBuilderExtensions.cs @@ -1,10 +1,9 @@ -using Microsoft.Extensions.Configuration; +using Cnblogs.Serilog.Extensions; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Serilog; -using Serilog.Extensions.Hosting; using Serilog.Extensions.Logging; using System; -using static Serilog.SerilogHostBuilderExtensions; namespace Microsoft.Extensions.Logging { @@ -239,5 +238,30 @@ public static ILoggingBuilder AddSerilog( preserveStaticLogger: preserveStaticLogger, writeToProviders: writeToProviders); } + + private static void ConfigureDiagnosticContext(IServiceCollection collection, bool useRegisteredLogger) + { + if (collection == null) throw new ArgumentNullException(nameof(collection)); + + // Registered to provide two services... + // Consumed by e.g. middleware + collection.AddSingleton(services => + { + Serilog.ILogger logger = useRegisteredLogger ? services.GetRequiredService().Logger : null; + return new DiagnosticContext(logger); + }); + // Consumed by user code + collection.AddSingleton(services => services.GetRequiredService()); + } + + private class RegisteredLogger + { + public RegisteredLogger(Serilog.ILogger logger) + { + Logger = logger; + } + + public Serilog.ILogger Logger { get; } + } } } \ No newline at end of file diff --git a/test/Serilog.Extensions.Hosting.Tests/DiagnosticContextTests.cs b/test/Serilog.Extensions.Hosting.Tests/DiagnosticContextTests.cs index c3fbb1d..20e2662 100644 --- a/test/Serilog.Extensions.Hosting.Tests/DiagnosticContextTests.cs +++ b/test/Serilog.Extensions.Hosting.Tests/DiagnosticContextTests.cs @@ -1,13 +1,11 @@ -using System; -using System.Linq; -using System.Threading.Tasks; +using Serilog; using Serilog.Events; -using Serilog.Extensions.Hosting.Tests.Support; +using Cnblogs.Serilog.Extensions.Tests.Support; using Xunit; // ReSharper disable PossibleNullReferenceException -namespace Serilog.Extensions.Hosting.Tests +namespace Cnblogs.Serilog.Extensions.Tests { public class DiagnosticContextTests { @@ -116,4 +114,4 @@ public void ExistingExceptionCanBeUpdated() Assert.Equal("ex2", collectedException.Message); } } -} +} \ No newline at end of file diff --git a/test/Serilog.Extensions.Hosting.Tests/LoggerSettingsConfigurationExtensionsTests.cs b/test/Serilog.Extensions.Hosting.Tests/LoggerSettingsConfigurationExtensionsTests.cs index 54a8154..0095da9 100644 --- a/test/Serilog.Extensions.Hosting.Tests/LoggerSettingsConfigurationExtensionsTests.cs +++ b/test/Serilog.Extensions.Hosting.Tests/LoggerSettingsConfigurationExtensionsTests.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; +using Cnblogs.Serilog.Extensions.Tests.Support; using Microsoft.Extensions.DependencyInjection; +using Serilog; using Serilog.Core; using Serilog.Events; -using Serilog.Extensions.Hosting.Tests.Support; using Xunit; -namespace Serilog.Extensions.Hosting.Tests +namespace Cnblogs.Serilog.Extensions.Tests { public class LoggerSettingsConfigurationExtensionsTests { @@ -13,7 +13,7 @@ public class LoggerSettingsConfigurationExtensionsTests public void SinksAreInjectedFromTheServiceProvider() { var emittedEvents = new List(); - + var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(new ListSink(emittedEvents)); using var services = serviceCollection.BuildServiceProvider(); @@ -21,9 +21,9 @@ public void SinksAreInjectedFromTheServiceProvider() using var logger = new LoggerConfiguration() .ReadFrom.Services(services) .CreateLogger(); - + logger.Information("Hello, world!"); - + var evt = Assert.Single(emittedEvents); Assert.Equal("Hello, world!", evt!.MessageTemplate.Text); } diff --git a/test/Serilog.Extensions.Hosting.Tests/ReloadableLoggerTests.cs b/test/Serilog.Extensions.Hosting.Tests/ReloadableLoggerTests.cs index 10b807a..437d05b 100644 --- a/test/Serilog.Extensions.Hosting.Tests/ReloadableLoggerTests.cs +++ b/test/Serilog.Extensions.Hosting.Tests/ReloadableLoggerTests.cs @@ -1,13 +1,12 @@ #if !NO_RELOADABLE_LOGGER -using System.Collections.Generic; -using System.Linq; +using Cnblogs.Serilog.Extensions.Tests.Support; +using Serilog; using Serilog.Core; using Serilog.Events; -using Serilog.Extensions.Hosting.Tests.Support; using Xunit; -namespace Serilog.Extensions.Hosting.Tests +namespace Cnblogs.Serilog.Extensions.Tests { public class ReloadableLoggerTests { @@ -18,14 +17,14 @@ public void AFrozenLoggerYieldsSerilogLoggers() var contextual = logger.ForContext(); var nested = contextual.ForContext("test", "test"); - Assert.IsNotType(nested); + Assert.IsNotType(nested); logger.Freeze(); nested = contextual.ForContext("test", "test"); - Assert.IsType(nested); + Assert.IsType(nested); } - + [Fact] public void CachingReloadableLoggerRemainsUsableAfterFreezing() { @@ -51,9 +50,9 @@ public void ReloadableLoggerRespectsMinimumLevelOverrides() var limited = logger .ForContext("X", 1) .ForContext(Constants.SourceContextPropertyName, "Test.Stuff"); - + var notLimited = logger.ForContext(); - + foreach (var context in new[] { limited, notLimited }) { // Suppressed by both sinks @@ -61,11 +60,11 @@ public void ReloadableLoggerRespectsMinimumLevelOverrides() // Suppressed by the limited logger context.Information("Second"); - + // Emitted by both loggers context.Warning("Third"); } - + Assert.Equal(3, emittedEvents.Count); Assert.Equal(2, emittedEvents.Count(le => le.Level == LogEventLevel.Warning)); } @@ -74,7 +73,7 @@ public void ReloadableLoggerRespectsMinimumLevelOverrides() public void ReloadableLoggersRecordEnrichment() { var emittedEvents = new List(); - + var logger = new LoggerConfiguration() .WriteTo.Sink(new ListSink(emittedEvents)) .CreateBootstrapLogger(); @@ -82,27 +81,27 @@ public void ReloadableLoggersRecordEnrichment() var outer = logger .ForContext("A", new object()); var inner = outer.ForContext("B", "test"); - + inner.Information("First"); - + logger.Reload(lc => lc.WriteTo.Sink(new ListSink(emittedEvents))); - + inner.Information("Second"); logger.Freeze(); - + inner.Information("Third"); - + outer.ForContext("B", "test").Information("Fourth"); - + logger.ForContext("A", new object()) .ForContext("B", "test") .Information("Fifth"); - + Assert.Equal(5, emittedEvents.Count); Assert.All(emittedEvents, e => Assert.Equal(2, e.Properties.Count)); } } } -#endif +#endif \ No newline at end of file diff --git a/test/Serilog.Extensions.Hosting.Tests/SerilogHostBuilderExtensionsTests.cs b/test/Serilog.Extensions.Hosting.Tests/SerilogHostBuilderExtensionsTests.cs deleted file mode 100644 index c9ba14b..0000000 --- a/test/Serilog.Extensions.Hosting.Tests/SerilogHostBuilderExtensionsTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Xunit; - -namespace Serilog.Extensions.Hosting.Tests -{ - public class SerilogHostBuilderExtensionsTests - { - [Fact] - public void ServicesAreRegisteredWhenCallingUseSerilog() - { - // Arrange - var collection = new ServiceCollection(); - IHostBuilder builder = new FakeHostBuilder(collection); - - // Act - builder.UseSerilog(); - - // Assert - IServiceProvider provider = collection.BuildServiceProvider(); - provider.GetRequiredService(); - provider.GetRequiredService(); - } - - [Fact] - public void ServicesAreRegisteredWhenCallingUseSerilogWithLogger() - { - // Arrange - var collection = new ServiceCollection(); - IHostBuilder builder = new FakeHostBuilder(collection); - ILogger logger = new LoggerConfiguration().CreateLogger(); - - // Act - builder.UseSerilog(logger); - - // Assert - IServiceProvider provider = collection.BuildServiceProvider(); - provider.GetRequiredService(); - provider.GetRequiredService(); - provider.GetRequiredService(); - } - - [Fact] - public void ServicesAreRegisteredWhenCallingUseSerilogWithConfigureDelegate() - { - // Arrange - var collection = new ServiceCollection(); - IHostBuilder builder = new FakeHostBuilder(collection); - - // Act - builder.UseSerilog((_, _) => { }); - - // Assert - IServiceProvider provider = collection.BuildServiceProvider(); - provider.GetRequiredService(); - provider.GetRequiredService(); - provider.GetRequiredService(); - } - - private class FakeHostBuilder : IHostBuilder - { - private readonly IServiceCollection _collection; - - public FakeHostBuilder(IServiceCollection collection) => _collection = collection; - - public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) - { - throw new NotImplementedException(); - } - - public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) - { - throw new NotImplementedException(); - } - - public IHostBuilder ConfigureServices(Action configureDelegate) - { - configureDelegate(null, _collection); - return this; - } - - public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) - { - throw new NotImplementedException(); - } - - public IHostBuilder UseServiceProviderFactory(Func> factory) - { - throw new NotImplementedException(); - } - - public IHostBuilder ConfigureContainer(Action configureDelegate) - { - throw new NotImplementedException(); - } - - public IHost Build() - { - throw new NotImplementedException(); - } - - public IDictionary Properties { get; } - } - } -} diff --git a/test/Serilog.Extensions.Hosting.Tests/SerilogLoggingBuilderExtensionsTests.cs b/test/Serilog.Extensions.Hosting.Tests/SerilogLoggingBuilderExtensionsTests.cs index 1f71a95..9c15a4b 100644 --- a/test/Serilog.Extensions.Hosting.Tests/SerilogLoggingBuilderExtensionsTests.cs +++ b/test/Serilog.Extensions.Hosting.Tests/SerilogLoggingBuilderExtensionsTests.cs @@ -1,11 +1,12 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Logging; +using Serilog; using Serilog.Sinks.InMemory; using Serilog.Sinks.InMemory.Assertions; using Xunit; -namespace Serilog.Extensions.Hosting.Tests; +namespace Cnblogs.Serilog.Extensions.Tests; public class SerilogLoggingBuilderExtensionsTests { diff --git a/test/Serilog.Extensions.Hosting.Tests/Support/DisposeTrackingLogger.cs b/test/Serilog.Extensions.Hosting.Tests/Support/DisposeTrackingLogger.cs index 6a090d1..eec1c71 100644 --- a/test/Serilog.Extensions.Hosting.Tests/Support/DisposeTrackingLogger.cs +++ b/test/Serilog.Extensions.Hosting.Tests/Support/DisposeTrackingLogger.cs @@ -1,9 +1,8 @@ -using System; -using System.Collections.Generic; +using Serilog; using Serilog.Core; using Serilog.Events; -namespace Serilog.Extensions.Hosting.Tests.Support +namespace Cnblogs.Serilog.Extensions.Tests.Support { public class DisposeTrackingLogger : ILogger, IDisposable { @@ -351,4 +350,4 @@ public void Dispose() IsDisposed = true; } } -} +} \ No newline at end of file diff --git a/test/Serilog.Extensions.Hosting.Tests/Support/ListSink.cs b/test/Serilog.Extensions.Hosting.Tests/Support/ListSink.cs index e94caaf..26d6143 100644 --- a/test/Serilog.Extensions.Hosting.Tests/Support/ListSink.cs +++ b/test/Serilog.Extensions.Hosting.Tests/Support/ListSink.cs @@ -5,7 +5,7 @@ using Serilog.Core; using Serilog.Events; -namespace Serilog.Extensions.Hosting.Tests.Support +namespace Cnblogs.Serilog.Extensions.Tests.Support { public class ListSink : ILogEventSink { diff --git a/test/Serilog.Extensions.Hosting.Tests/Support/Some.cs b/test/Serilog.Extensions.Hosting.Tests/Support/Some.cs index 5137cef..abfd793 100644 --- a/test/Serilog.Extensions.Hosting.Tests/Support/Some.cs +++ b/test/Serilog.Extensions.Hosting.Tests/Support/Some.cs @@ -1,14 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; +using Serilog; using Serilog.Events; -namespace Serilog.Extensions.Hosting.Tests.Support +namespace Cnblogs.Serilog.Extensions.Tests.Support { - static class Some + internal static class Some { - static int _next; + private static int _next; public static int Int32() => Interlocked.Increment(ref _next); @@ -18,4 +15,4 @@ static class Some public static ILogger Logger() => new LoggerConfiguration().CreateLogger(); } -} +} \ No newline at end of file