Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup #219

Closed
wants to merge 13 commits into from
3 changes: 0 additions & 3 deletions Directory.Build.targets

This file was deleted.

7 changes: 7 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "7.0.201",
"allowPrerelease": false,
"rollForward": "latestFeature"
}
}
108 changes: 50 additions & 58 deletions samples/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,75 +3,67 @@
using Serilog;
using Serilog.Extensions.Logging;

namespace Sample;
// Creating a `LoggerProviderCollection` lets Serilog optionally write
// events through other dynamically-added MEL ILoggerProviders.
var providers = new LoggerProviderCollection();

public class Program
{
public static void Main(string[] args)
{
// Creating a `LoggerProviderCollection` lets Serilog optionally write
// events through other dynamically-added MEL ILoggerProviders.
var providers = new LoggerProviderCollection();

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.Providers(providers)
.CreateLogger();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.Providers(providers)
.CreateLogger();

var services = new ServiceCollection();
var services = new ServiceCollection();

services.AddSingleton(providers);
services.AddSingleton<ILoggerFactory>(sc =>
{
var providerCollection = sc.GetService<LoggerProviderCollection>();
var factory = new SerilogLoggerFactory(null, true, providerCollection);
services.AddSingleton(providers);
services.AddSingleton<ILoggerFactory>(sc =>
{
var providerCollection = sc.GetService<LoggerProviderCollection>();
var factory = new SerilogLoggerFactory(null, true, providerCollection);

foreach (var provider in sc.GetServices<ILoggerProvider>())
factory.AddProvider(provider);
foreach (var provider in sc.GetServices<ILoggerProvider>())
factory.AddProvider(provider);

return factory;
});
return factory;
});

services.AddLogging(l => l.AddConsole());
services.AddLogging(l => l.AddConsole());

var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();

var startTime = DateTimeOffset.UtcNow;
logger.LogInformation(1, "Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);
var startTime = DateTimeOffset.UtcNow;
logger.LogInformation(1, "Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

try
{
throw new Exception("Boom!");
}
catch (Exception ex)
{
logger.LogCritical("Unexpected critical error starting application", ex);
logger.Log(LogLevel.Critical, 0, "Unexpected critical error", ex, null!);
// This write should not log anything
logger.Log<object>(LogLevel.Critical, 0, null!, null, null!);
logger.LogError("Unexpected error", ex);
logger.LogWarning("Unexpected warning", ex);
}
try
{
throw new Exception("Boom!");
}
catch (Exception ex)
{
logger.LogCritical("Unexpected critical error starting application", ex);
logger.Log(LogLevel.Critical, 0, "Unexpected critical error", ex, null!);
// This write should not log anything
logger.Log<object>(LogLevel.Critical, 0, null!, null, null!);
logger.LogError("Unexpected error", ex);
logger.LogWarning("Unexpected warning", ex);
}

using (logger.BeginScope("Main"))
{
logger.LogInformation("Waiting for user input");
var key = Console.Read();
logger.LogInformation("User pressed {@KeyInfo}", new { Key = key, KeyChar = (char)key });
}
using (logger.BeginScope("Main"))
{
logger.LogInformation("Waiting for user input");
var key = Console.Read();
logger.LogInformation("User pressed {@KeyInfo}", new { Key = key, KeyChar = (char)key });
}

var endTime = DateTimeOffset.UtcNow;
logger.LogInformation(2, "Stopping at {StopTime}", endTime);
var endTime = DateTimeOffset.UtcNow;
logger.LogInformation(2, "Stopping at {StopTime}", endTime);

logger.LogInformation("Stopping");
logger.LogInformation("Stopping");

logger.LogInformation(Environment.NewLine);
logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "RESULT", "START TIME", "END TIME", "DURATION(ms)");
logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "------", "----- ----", "--- ----", "------------");
logger.LogInformation("{Result,-10:l}{StartTime,15:mm:s tt}{EndTime,15:mm:s tt}{Duration,15}", "SUCCESS", startTime, endTime, (endTime - startTime).TotalMilliseconds);
logger.LogInformation(Environment.NewLine);
logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "RESULT", "START TIME", "END TIME", "DURATION(ms)");
logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "------", "----- ----", "--- ----", "------------");
logger.LogInformation("{Result,-10:l}{StartTime,15:mm:s tt}{EndTime,15:mm:s tt}{Duration,15}", "SUCCESS", startTime, endTime, (endTime - startTime).TotalMilliseconds);

serviceProvider.Dispose();
}
}
serviceProvider.Dispose();
3 changes: 0 additions & 3 deletions samples/Sample/Properties/launchSettings.json

This file was deleted.

2 changes: 1 addition & 1 deletion serilog-extensions-logging.sln
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{9C21B9
appveyor.yml = appveyor.yml
Build.ps1 = Build.ps1
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
README.md = README.md
assets\Serilog.snk = assets\Serilog.snk
global.json = global.json
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Extensions.Logging.Benchmarks", "test\Serilog.Extensions.Logging.Benchmarks\Serilog.Extensions.Logging.Benchmarks.csproj", "{6D5986FF-EECD-4E75-8BC6-A5F78AB549B2}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,11 @@ public LoggerProviderCollectionSink(LoggerProviderCollection providers)

public void Emit(LogEvent logEvent)
{
string categoryName = "None";
var categoryName = "None";
EventId eventId = default;

if (logEvent.Properties.TryGetValue("SourceContext", out var sourceContextProperty) &&
sourceContextProperty is ScalarValue sourceContextValue &&
sourceContextValue.Value is string sourceContext)
sourceContextProperty is ScalarValue {Value: string sourceContext})
{
categoryName = sourceContext;
}
Expand All @@ -44,8 +43,8 @@ sourceContextProperty is ScalarValue sourceContextValue &&
var id = 0;
foreach (var item in structuredEventId.Properties)
{
if (item.Name == "Id" && item.Value is ScalarValue sv && sv.Value is int i) id = i;
if (item.Name == "Name" && item.Value is ScalarValue sv2 && sv2.Value is string s) name = s;
if (item is {Name: "Id", Value: ScalarValue {Value: int i}}) id = i;
if (item is {Name: "Name", Value: ScalarValue {Value: string s}}) name = s;
}

eventId = new EventId(id, name);
Expand All @@ -63,7 +62,7 @@ sourceContextProperty is ScalarValue sourceContextValue &&
eventId,
slv,
logEvent.Exception,
(s, e) => s.ToString());
(s, _) => s.ToString());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
}
catch (Exception ex)
{
SelfLog.WriteLine($"Failed to write event through {typeof(SerilogLogger).Name}: {ex}");
SelfLog.WriteLine($"Failed to write event through {nameof(SerilogLogger)}: {ex}");
}
}

Expand All @@ -95,7 +95,7 @@ void Write<TState>(LogEventLevel level, EventId eventId, TState state, Exception
{
foreach (var property in structure)
{
if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string value)
if (property is {Key: SerilogLoggerProvider.OriginalFormatPropertyName, Value: string value})
{
messageTemplate = value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
List<LogEventPropertyValue>? scopeItems = null;
for (var scope = CurrentScope; scope != null; scope = scope.Parent)
{
scope.EnrichAndCreateScopeItem(logEvent, propertyFactory, out LogEventPropertyValue? scopeItem);
scope.EnrichAndCreateScopeItem(logEvent, propertyFactory, out var scopeItem);

if (scopeItem != null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Serilog.Core;
using Serilog.Events;

Expand Down Expand Up @@ -85,7 +83,7 @@ void AddProperty(KeyValuePair<string, object> stateProperty)

foreach (var stateProperty in dictionary)
{
if (stateProperty.Key == SerilogLoggerProvider.OriginalFormatPropertyName && stateProperty.Value is string)
if (stateProperty is {Key: SerilogLoggerProvider.OriginalFormatPropertyName, Value: string})
scopeItem = new ScalarValue(_state.ToString());
else
AddProperty(stateProperty);
Expand All @@ -97,7 +95,7 @@ void AddProperty(KeyValuePair<string, object> stateProperty)

foreach (var stateProperty in stateProperties)
{
if (stateProperty.Key == SerilogLoggerProvider.OriginalFormatPropertyName && stateProperty.Value is string)
if (stateProperty is {Key: SerilogLoggerProvider.OriginalFormatPropertyName, Value: string})
scopeItem = new ScalarValue(_state.ToString());
else
AddProperty(stateProperty);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static ILoggingBuilder AddSerilog(this ILoggingBuilder builder, ILogger?

if (dispose)
{
builder.Services.AddSingleton<ILoggerProvider, SerilogLoggerProvider>(services => new SerilogLoggerProvider(logger, true));
builder.Services.AddSingleton<ILoggerProvider, SerilogLoggerProvider>(_ => new SerilogLoggerProvider(logger, true));
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public void LogsCorrectMessage()

logger.Log<object>(LogLevel.Information, 0, null!, null!, null!);
logger.Log(LogLevel.Information, 0, TestMessage, null!, null!);
logger.Log<object>(LogLevel.Information, 0, null!, null!, (_, __) => TestMessage);
logger.Log<object>(LogLevel.Information, 0, null!, null!, (_, _) => TestMessage);

Assert.Equal(3, sink.Writes.Count);

Expand Down