Skip to content
Open
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
7 changes: 7 additions & 0 deletions Ardalis.Result.sln
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ardalis.Result.FluentAssert
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ardalis.Result.FluentAssertions.UnitTests", "tests\Ardalis.Result.FluentAssertions.UnitTests\Ardalis.Result.FluentAssertions.UnitTests.csproj", "{0800019A-0B40-4923-96E1-656A745E79C2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ardalis.Result.SampleErrorsLogging", "sample\Ardalis.Result.SampleErrorsLogging\Ardalis.Result.SampleErrorsLogging.csproj", "{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -107,6 +109,10 @@ Global
{0800019A-0B40-4923-96E1-656A745E79C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0800019A-0B40-4923-96E1-656A745E79C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0800019A-0B40-4923-96E1-656A745E79C2}.Release|Any CPU.Build.0 = Release|Any CPU
{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -125,6 +131,7 @@ Global
{C522FE42-BBEF-46A7-9E3E-44EA8339AF2E} = {42693FB1-04E1-4635-B249-E1847609E801}
{94145FF9-5A56-4479-87AF-3A99939B38F0} = {865A74CD-F478-4AA5-AFA5-6C26FB38B849}
{0800019A-0B40-4923-96E1-656A745E79C2} = {42693FB1-04E1-4635-B249-E1847609E801}
{15C8FBAA-02CC-65F4-28FA-3E8D73211E8D} = {FA061DC6-61B7-401F-87A4-D338B396CCD9}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7CD0ED8C-3B1C-4F16-8B8D-3D8F1A8F1A5A}
Expand Down
66 changes: 36 additions & 30 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,32 +1,38 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Ardalis.ApiEndpoints" Version="4.1.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="FluentAssertions" Version="7.0.0" />
<PackageVersion Include="FluentValidation" Version="11.9.2" />
<PackageVersion Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.3" />
<PackageVersion Include="Microsoft.Extensions.Localization.Abstractions" Version="8.0.8" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Microsoft.TestPlatform.ObjectModel" Version="17.5.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.4" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageVersion Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageVersion Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageVersion Include="System.Runtime" Version="4.3.1" />
<PackageVersion Include="System.Text.Json" Version="8.0.4" />
<PackageVersion Include="xunit" Version="2.4.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" />
</ItemGroup>
<ItemGroup Condition="'$(IsPackable)' == 'true'">
<GlobalPackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))" />
</ItemGroup>
<ItemGroup>
<GlobalPackageReference Include="PolySharp" Version="1.13.2" />
</ItemGroup>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Ardalis.ApiEndpoints" Version="4.1.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="FluentAssertions" Version="7.0.0" />
<PackageVersion Include="FluentValidation" Version="11.9.2" />
<PackageVersion Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.3" />
<PackageVersion Include="Microsoft.Extensions.Localization.Abstractions" Version="8.0.8" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Microsoft.TestPlatform.ObjectModel" Version="17.5.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.4" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageVersion Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageVersion Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageVersion Include="System.Runtime" Version="4.3.1" />
<PackageVersion Include="System.Text.Json" Version="8.0.4" />
<PackageVersion Include="xunit" Version="2.4.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" />

<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
<PackageVersion Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageVersion Include="Serilog.Sinks.OpenTelemetry" Version="4.1.1" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(IsPackable)' == 'true'">
<GlobalPackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))" />
</ItemGroup>
<ItemGroup>
<GlobalPackageReference Include="PolySharp" Version="1.13.2" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Serilog.Extensions.Hosting" />
<PackageReference Include="Serilog.Sinks.File" />
<PackageReference Include="Serilog.Sinks.OpenTelemetry" />
<PackageReference Include="Serilog.Sinks.Console" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Ardalis.Result.Sample.Core\Ardalis.Result.Sample.Core.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Ardalis.Result.ErrorsLoggingDemo;

public record BasicContext(
string CalledBy,
string CorrelationId,
Dictionary<string, string> ExtraInfo);
6 changes: 6 additions & 0 deletions sample/Ardalis.Result.SampleErrorsLogging/Logging/EventIds.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Ardalis.Result.ErrorsLoggingDemo;

internal static class EventIds
{
public const int ResultErrors = 1000;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Runtime.CompilerServices;

namespace Ardalis.Result.ErrorsLoggingDemo;

public record ResultErrorsDetails(
string[] Errors);

public static partial class ILoggerExtenders
{
public static void LogResultErrors(
this ILogger logger,
Result result,
Dictionary<string, string> extraInfo = null!,
Guid correlationId = default,
[CallerMemberName] string calledBy = "")
{
if (!result.IsError())
return;

logger.ResultErrors(
new ResultErrorsDetails([.. result.Errors]),
new BasicContext(calledBy, result
.GetCorrelationId(correlationId), extraInfo));
}

[LoggerMessage(
EventId = EventIds.ResultErrors,
EventName = nameof(ResultErrors),
Level = LogLevel.Information,
SkipEnabledCheck = true,
Message = $"{nameof(ResultErrors)}={{@Details}};Context={{@Context}}")]
private static partial void ResultErrors(
this ILogger logger,
ResultErrorsDetails details,
BasicContext context);
}
50 changes: 50 additions & 0 deletions sample/Ardalis.Result.SampleErrorsLogging/Logging/LoggerBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Serilog;
using Serilog.Sinks.OpenTelemetry;
using MEL = Microsoft.Extensions.Logging;

namespace Ardalis.Result.ErrorsLoggingDemo;

public class LoggerBuilder
{
// Builds and then returns an initialized
// Microsoft.Extension.Logging.ILogger
public static MEL.ILogger Build(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false,false)
.Build();

var seqApiUri = new Uri(config["Serilog:SeqApiUri"]!);

var seqApiKey = config["Serilog:SeqApiKey"]!;

var logLevel = (LogLevel)Enum.Parse(typeof(LogLevel),
config["Serilog:LogLevel"]! ?? "Debug");

SerilogHelper.InitLogDotLogger(logLevel, configure =>
{
// One of these need to be specified for each
// logged "details" type
configure.OmitTypeField<ResultErrorsDetails>();

configure.WriteTo.OpenTelemetry(x =>
{
x.Endpoint = seqApiUri.AbsoluteUri;
x.Protocol = OtlpProtocol.HttpProtobuf;
x.Headers = new Dictionary<string, string>
{
["X-Seq-ApiKey"] = seqApiKey
};
x.ResourceAttributes = new Dictionary<string, object>
{
["service.name"] = "ResultErrorsLoggingDemo"
};
});
});

using var loggerFactory = LoggerFactory.Create(
builder => { builder.AddSerilog(); });

return loggerFactory.CreateLogger<Program>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Ardalis.Result.ErrorsLoggingDemo;

public class LoggingException(string message)
: Exception(message)
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Ardalis.Result.ErrorsLoggingDemo;

public static class LoggingHelpers
{
public static string GetCorrelationId(
this Result result, Guid correlationId)
{
if (correlationId != default)
return correlationId.ToString("N");
else if (string.IsNullOrEmpty(result.CorrelationId))
return Guid.NewGuid().ToString("N");
else
return result.CorrelationId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Serilog;

namespace Ardalis.Result.ErrorsLoggingDemo;

public static class SerilogExtenders
{
public static LoggerConfiguration OmitTypeField<T>(
this LoggerConfiguration loggerConfiguration)
{
return loggerConfiguration
.Destructure.ByTransforming<T>(instance =>
{
var properties = instance!.GetType()
.GetProperties().Where(p => p.Name != "$type")
.ToDictionary(p => p.Name, p => p.GetValue(instance));

return properties;
});
}
}
48 changes: 48 additions & 0 deletions sample/Ardalis.Result.SampleErrorsLogging/Logging/SerilogHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
using System.Diagnostics;

namespace Ardalis.Result.ErrorsLoggingDemo;

public static class SerilogHelper
{
public static void InitLogDotLogger(
LogLevel minLogLevel = LogLevel.Information,
Action<LoggerConfiguration> configure = null!)
{
Serilog.Debugging.SelfLog.Enable(
output => Debug.WriteLine(output));

Serilog.Debugging.SelfLog.Enable(Console.Error);

var config = new LoggerConfiguration()
.MinimumLevel.Is(minLogLevel.ToLogEventLevel())
.OmitTypeField<BasicContext>()
.Destructure.ByTransforming<DateTime>(v => v.ToString("MM/dd/yyyy HH:mm:ss.fff"))
.Destructure.ByTransforming<Enum>(v => v.ToString())
.Destructure.ByTransforming<Guid>(v => v.ToString("D"))
.Destructure.ByTransforming<TimeSpan>(v => v.ToString(@"d\.hh\:mm\:ss\.fff"));

config.Enrich.FromLogContext();

config.WriteTo.Console(theme: AnsiConsoleTheme.Code, outputTemplate:
"[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}");

configure?.Invoke(config);

Log.Logger = config.CreateLogger();
}

public static LogEventLevel ToLogEventLevel(this LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Debug => LogEventLevel.Debug,
LogLevel.Information => LogEventLevel.Information,
LogLevel.Warning => LogEventLevel.Warning,
LogLevel.Error => LogEventLevel.Error,
_ => throw new LoggingException("A valid \"logLevel\" must be supplied.")
};
}
}
25 changes: 25 additions & 0 deletions sample/Ardalis.Result.SampleErrorsLogging/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Ardalis.Result;
using Ardalis.Result.ErrorsLoggingDemo;
using Serilog;

// Build a configured logger
var logger = LoggerBuilder.Build(args);

// A custom CorrelationId
var correlationId = Guid.NewGuid();

// Logs Result Errors, with optional ExtraInfo and an optional
// CorrelationId override, If a CorrelationId is not provided,
// it will be taken from Result.CorrelationId (if it exists)
// or created using Guid.NewGuid().
logger.LogResultErrors(
Result.Error(new ErrorList(["Oops!", "Whoopsie!"])),
new Dictionary<string, string>
{
{ "Code", "ABC123" },
{ "Number", "987654321" }
},
correlationId);

// Always close and flush before terminating your app
Log.CloseAndFlush();
14 changes: 14 additions & 0 deletions sample/Ardalis.Result.SampleErrorsLogging/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Serilog": {
"SeqApiUri": "http://localhost:5341/ingest/otlp/v1/logs",
"SeqApiKey": "",
"LogLevel": "Debug"
}
}