Skip to content

Commit

Permalink
Merge pull request #7 from cnblogs/remove-hostbuilder-extensions
Browse files Browse the repository at this point in the history
refactor: remove SerilogHostBuilderExtensions
  • Loading branch information
cnblogs-dudu authored Feb 12, 2023
2 parents 46cdd0a + 85e4142 commit cf34ff0
Show file tree
Hide file tree
Showing 26 changed files with 168 additions and 477 deletions.
15 changes: 8 additions & 7 deletions samples/SimpleServiceSample/Program.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down Expand Up @@ -36,9 +36,10 @@ public static int Main(string[] args)
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services => services.AddHostedService<PrintTimeService>())
.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()));
}
}
}
8 changes: 5 additions & 3 deletions samples/WebApplicationSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -17,7 +18,7 @@ public static int Main(string[] args)
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();

Log.Information("Starting up!");

try
Expand All @@ -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<Startup>(); });
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
using System;
using System.Threading;

namespace Serilog.Extensions.Hosting
namespace Cnblogs.Serilog.Extensions
{
class AmbientDiagnosticContextCollector : IDisposable
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ILogger, ILogger> _configure;
readonly IReloadableLogger _parent;

ILogger _root, _cached;
bool _frozen;

Expand All @@ -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,
Expand All @@ -72,14 +73,14 @@ public ILogger ForContext(ILogEventEnricher enricher)
public ILogger ForContext(IEnumerable<ILogEventEnricher> 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,
Expand All @@ -95,7 +96,7 @@ public ILogger ForContext(IEnumerable<ILogEventEnricher> enrichers)
public ILogger ForContext(string propertyName, object value, bool destructureObjects = false)
{
if (propertyName == null) return this;

if (_frozen)
return _cached.ForContext(propertyName, value, destructureObjects);

Expand Down Expand Up @@ -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,
Expand All @@ -148,11 +149,11 @@ public ILogger ForContext<TSource>()
{
if (_frozen)
return _cached.ForContext<TSource>();

if (_reloadableLogger.CreateChild(
_root,
this,
_cached,
_cached,
p => p.ForContext<TSource>(),
out var child,
out var newRoot,
Expand All @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -486,7 +487,7 @@ public bool IsEnabled(LogEventLevel level)

return isEnabled;
}

public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate,
out IEnumerable<LogEventProperty> boundProperties)
{
Expand Down Expand Up @@ -542,4 +543,4 @@ public bool BindProperty(string propertyName, object value, bool destructureObje
}
}

#endif
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@
// 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
{
/// <summary>
/// Implements an ambient diagnostic context using <see cref="AsyncLocal{T}"/>.
/// </summary>
/// <remarks>Consumers should use <see cref="IDiagnosticContext"/> to set context properties.</remarks>
public sealed class DiagnosticContext : IDiagnosticContext
{
readonly ILogger _logger;
private readonly ILogger _logger;

/// <summary>
/// Construct a <see cref="DiagnosticContext"/>.
Expand All @@ -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);
Expand All @@ -64,4 +65,4 @@ public void SetException(Exception exception)
collector?.SetException(exception);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
using System.Collections.Generic;
using Serilog.Events;

namespace Serilog.Extensions.Hosting
namespace Cnblogs.Serilog.Extensions
{
/// <summary>
/// A container that receives properties added to a diagnostic context.
/// </summary>
public sealed class DiagnosticContextCollector : IDisposable
{
readonly IDisposable _chainedDisposable;
readonly object _propertiesLock = new object();
Exception _exception;
Dictionary<string, LogEventProperty> _properties = new Dictionary<string, LogEventProperty>();
private readonly IDisposable _chainedDisposable;
private readonly object _propertiesLock = new object();
private Exception _exception;
private Dictionary<string, LogEventProperty> _properties = new Dictionary<string, LogEventProperty>();

/// <summary>
/// Construct a <see cref="DiagnosticContextCollector"/>.
Expand Down Expand Up @@ -84,7 +84,7 @@ public bool TryComplete(out IEnumerable<LogEventProperty> properties)
/// <param name="exception">The collected exception, or null if none has been collected or if no collection is active.</param>
/// <returns>True if properties could be collected.</returns>
/// <seealso cref="IDiagnosticContext.Set"/>
/// <seealso cref="Serilog.IDiagnosticContext.SetException"/>
/// <seealso cref="IDiagnosticContext.SetException"/>
public bool TryComplete(out IEnumerable<LogEventProperty> properties, out Exception exception)
{
lock (_propertiesLock)
Expand All @@ -104,4 +104,4 @@ public void Dispose()
_chainedDisposable.Dispose();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
using Serilog.Core;
using Serilog.Events;

namespace Serilog.Extensions.Hosting
namespace Cnblogs.Serilog.Extensions
{
class FixedPropertyEnricher : ILogEventEnricher
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
{
Expand All @@ -19,7 +20,7 @@ public void Configure(LoggerConfiguration loggerConfiguration)
var levelSwitch = _services.GetService<LoggingLevelSwitch>();
if (levelSwitch != null)
loggerConfiguration.MinimumLevel.ControlledBy(levelSwitch);

foreach (var settings in _services.GetServices<ILoggerSettings>())
loggerConfiguration.ReadFrom.Settings(settings);

Expand All @@ -28,12 +29,12 @@ public void Configure(LoggerConfiguration loggerConfiguration)

foreach (var enricher in _services.GetServices<ILogEventEnricher>())
loggerConfiguration.Enrich.With(enricher);

foreach (var filter in _services.GetServices<ILogEventFilter>())
loggerConfiguration.Filter.With(filter);

foreach (var sink in _services.GetServices<ILogEventSink>())
loggerConfiguration.WriteTo.Sink(sink);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading

0 comments on commit cf34ff0

Please sign in to comment.