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

Implicit usings and file-scoped namespaces #342

Merged
merged 1 commit into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ end_of_line = lf

[*.{cmd, bat}]
end_of_line = crlf

csharp_style_namespace_declarations = file_scoped:suggestion
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<TreatSpecificWarningsAsErrors />
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
Expand Down
136 changes: 64 additions & 72 deletions sample/Sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
using System;

using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;

using Serilog;
using Serilog.Core;
Expand All @@ -14,93 +7,92 @@

// ReSharper disable UnusedType.Global

namespace Sample
namespace Sample;

public class Program
{
public class Program
public static void Main(string[] args)
{
public static void Main(string[] args)
{
SelfLog.Enable(Console.Error);
SelfLog.Enable(Console.Error);

Thread.CurrentThread.Name = "Main thread";
Thread.CurrentThread.Name = "Main thread";

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

logger.Information("Args: {Args}", args);
logger.Information("Args: {Args}", args);

do
{
logger.ForContext<Program>().Information("Hello, world!");
logger.ForContext<Program>().Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Warning("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!");
do
{
logger.ForContext<Program>().Information("Hello, world!");
logger.ForContext<Program>().Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Warning("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!");

logger.Information("Destructure with max object nesting depth:\n{@NestedObject}",
new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } });
logger.Information("Destructure with max object nesting depth:\n{@NestedObject}",
new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } });

logger.Information("Destructure with max string length:\n{@LongString}",
new { TwentyChars = "0123456789abcdefghij" });
logger.Information("Destructure with max string length:\n{@LongString}",
new { TwentyChars = "0123456789abcdefghij" });

logger.Information("Destructure with max collection count:\n{@BigData}",
new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } });
logger.Information("Destructure with max collection count:\n{@BigData}",
new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } });

logger.Information("Destructure with policy to strip password:\n{@LoginData}",
new LoginData { Username = "BGates", Password = "isityearoflinuxyet" });
logger.Information("Destructure with policy to strip password:\n{@LoginData}",
new LoginData { Username = "BGates", Password = "isityearoflinuxyet" });

Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n");
}
while (!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n");
}
while (!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
}
}

// The filter syntax in the sample configuration file is
// processed by the Serilog.Filters.Expressions package.
public class CustomFilter : ILogEventFilter
{
readonly LogEventLevel _levelFilter;

public CustomFilter(LogEventLevel levelFilter = LogEventLevel.Information)
{
_levelFilter = levelFilter;
}
// The filter syntax in the sample configuration file is
// processed by the Serilog.Filters.Expressions package.
public class CustomFilter : ILogEventFilter
{
readonly LogEventLevel _levelFilter;

public bool IsEnabled(LogEvent logEvent)
{
return logEvent.Level >= _levelFilter;
}
public CustomFilter(LogEventLevel levelFilter = LogEventLevel.Information)
{
_levelFilter = levelFilter;
}

public class LoginData
public bool IsEnabled(LogEvent logEvent)
{
public string Username;
// ReSharper disable once NotAccessedField.Global
public string Password;
return logEvent.Level >= _levelFilter;
}
}

public class LoginData
{
public string Username;
// ReSharper disable once NotAccessedField.Global
public string Password;
}

public class CustomPolicy : IDestructuringPolicy
public class CustomPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
result = null;

if (value is LoginData loginData)
{
result = null;

if (value is LoginData loginData)
{
result = new StructureValue(
new List<LogEventProperty>
{
new("Username", new ScalarValue(loginData.Username))
});
}

return (result != null);
result = new StructureValue(
new List<LogEventProperty>
{
new("Username", new ScalarValue(loginData.Username))
});
}

return (result != null);
}
}
16 changes: 8 additions & 8 deletions serilog-settings-configuration.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">


<s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/AutoCompleteBasicCompletion/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/IntelliSenseCompletingCharacters/CSharpCompletingCharacters/UpgradedFromVSSettings/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/IntelliSenseCompletingCharacters/IntelliSenseCompletingCharactersSettingCSharp/UpgradedFromVSSettings/@EntryValue">True</s:Boolean>
Expand Down Expand Up @@ -477,7 +477,7 @@ II.2.12 &lt;HandlesEvent /&gt;&#xD;
&lt;/Patterns&gt;&#xD;
</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpMemberOrderPattern/LayoutType/@EntryValue">CustomLayout</s:String>

<s:Boolean x:Key="/Default/CodeStyle/Generate/=Constructor/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Generate/=Constructor/Options/=XmlDocumentation/@EntryIndexedValue">False</s:String>
<s:Boolean x:Key="/Default/CodeStyle/Generate/=Equality/@KeyIndexDefined">True</s:Boolean>
Expand Down Expand Up @@ -551,11 +551,11 @@ II.2.12 &lt;HandlesEvent /&gt;&#xD;
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsCodeFormatterSettingsUpgrader/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsParsFormattingSettingsUpgrader/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EJavaScript_002ECodeStyle_002ESettingsUpgrade_002EJsWrapperSettingsUpgrader/@EntryIndexedValue">True</s:Boolean>




<s:String x:Key="/Default/FilterSettingsManager/AttributeFilterXml/@EntryValue">&lt;data /&gt;</s:String>
<s:String x:Key="/Default/FilterSettingsManager/CoverageFilterXml/@EntryValue">&lt;data&gt;&lt;IncludeFilters /&gt;&lt;ExcludeFilters /&gt;&lt;/data&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Enricher/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=polyfilled/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/UserDictionary/Words/=polyfilled/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
Loading