Skip to content

Commit

Permalink
fix: 🐛 fix ci check formatting issue (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
mehdihadeli authored Sep 15, 2024
1 parent 28f9fe0 commit 0c80560
Show file tree
Hide file tree
Showing 24 changed files with 280 additions and 170 deletions.
7 changes: 0 additions & 7 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@
],
"rollForward": false
},
"dotnet-format": {
"version": "5.1.250801",
"commands": [
"dotnet-format"
],
"rollForward": false
},
"csharpier": {
"version": "0.29.0",
"commands": [
Expand Down
3 changes: 2 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ root = true

# Global settings
[*]
end_of_line = crlf
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

Expand Down
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
*.cs text eol=lf

###############################################################################
# Set default behavior for command prompt diff.
Expand Down
6 changes: 4 additions & 2 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
npm run format
npm run fix-analyzers
npm run fix-style
npm run fix-csharpier-format

npm run format
npm run style

npm run analyzers
7 changes: 7 additions & 0 deletions Vertical.Slice.Template.sln
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vertical.Slice.Template.Api
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "src\Shared\Shared.csproj", "{A5FB3B9E-FF0A-45F4-8D37-080C770A5AB4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".husky", ".husky", "{727B615D-D77D-4FEF-ADC6-66CA01B922C1}"
ProjectSection(SolutionItems) = preProject
.husky\commit-msg = .husky\commit-msg
.husky\pre-commit = .husky\pre-commit
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -126,6 +132,7 @@ Global
{AC478225-5EA9-4895-875A-0B01217C4576} = {AF80152C-AF0D-475E-AD69-A7867D1ACA26}
{23F3C3DD-6630-4743-BE50-9BD6F719665E} = {AF80152C-AF0D-475E-AD69-A7867D1ACA26}
{A5FB3B9E-FF0A-45F4-8D37-080C770A5AB4} = {54C91A04-E128-4ADB-9B49-E0FEAC783069}
{727B615D-D77D-4FEF-ADC6-66CA01B922C1} = {798579C1-7DEC-47A2-9C18-CA3DBE4A6573}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5F41BF51-E13B-48BF-8D81-874FBA9BC961}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
"prepare": "husky && dotnet tool restore",
"install-dev-cert-bash": "curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v vs2019 -l ~/vsdbg",
"upgrade-packages": "dotnet outdated Vertical.Slice.Template.sln",
"apply-formatting": "dotnet csharpier . && git add -A .",
"format": "dotnet csharpier . --check",
"style": "dotnet format style Vertical.Slice.Template.sln --verify-no-changes --severity error --verbosity diagnostic",
"analyzers": "dotnet format analyzers Vertical.Slice.Template.sln --verify-no-changes --severity error --verbosity diagnostic"
"analyzers": "dotnet format analyzers Vertical.Slice.Template.sln --verify-no-changes --severity error --verbosity diagnostic",
"fix-csharpier-format": "dotnet csharpier . && git add -A .",
"fix-style": "dotnet format style Vertical.Slice.Template.sln --severity error --verbosity diagnostic && git add -A .",
"fix-analyzers": "dotnet format analyzers Vertical.Slice.Template.sln --severity error --verbosity diagnostic && git add -A ."
},
"repository": {
"type": "git",
Expand All @@ -27,4 +29,3 @@
"husky": "^9.1.6"
}
}

2 changes: 1 addition & 1 deletion src/App/Vertical.Slice.Template.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Serilog;
using Serilog.Events;
using Shared.Logging;
using Shared.Logging.Extensions;
using Shared.Swagger;
using Shared.Web.Extensions;
using Shared.Web.Minimal.Extensions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,16 @@ internal static RouteHandlerBuilder MapCreateProductEndpoint(this IEndpointRoute
// StatusCodes.Status201Created,
// getId: response => response.Id
// );

return app.MapPost("/", Handle)
.WithName(nameof(CreateProduct))
.WithDisplayName(nameof(CreateProduct).Humanize())
.WithSummaryAndDescription(nameof(CreateProduct).Humanize(), nameof(CreateProduct).Humanize())
.WithTags(ProductConfigurations.Tag)
// .Produces<CreateProductResponse>("Product created successfully.", StatusCodes.Status201Created)
// .ProducesValidationProblem("Invalid input for creating product.", StatusCodes.Status400BadRequest)
// .ProducesProblem("UnAuthorized request.", StatusCodes.Status401Unauthorized)
.MapToApiVersion(1.0);
// .Produces<CreateProductResponse>("Product created successfully.", StatusCodes.Status201Created)
// .ProducesValidationProblem("Invalid input for creating product.", StatusCodes.Status400BadRequest)
// .ProducesProblem("UnAuthorized request.", StatusCodes.Status401Unauthorized)

async Task<
Results<CreatedAtRoute<CreateProductResponse>, UnAuthorizedHttpProblemResult, ValidationProblem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ internal static RouteHandlerBuilder MapGetProductByIdEndpoint(this IEndpointRout
.WithDisplayName(nameof(GetProductById).Humanize())
.WithSummaryAndDescription(nameof(GetProductById).Humanize(), nameof(GetProductById).Humanize())
.WithTags(ProductConfigurations.Tag)
// .Produces<GetProductByIdResponse>("Product fetched successfully.", StatusCodes.Status200OK)
// .ProducesValidationProblem("Invalid input for getting product.", StatusCodes.Status400BadRequest)
// .ProducesProblem("Product not found", StatusCodes.Status404NotFound)
.MapToApiVersion(1.0);
// .Produces<GetProductByIdResponse>("Product fetched successfully.", StatusCodes.Status200OK)
// .ProducesValidationProblem("Invalid input for getting product.", StatusCodes.Status400BadRequest)
// .ProducesProblem("Product not found", StatusCodes.Status404NotFound)

async Task<Results<Ok<GetProductByIdResponse>, ValidationProblem, NotFoundHttpProblemResult>> Handle(
[AsParameters] GetProductByIdRequestParameters requestParameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ internal static RouteHandlerBuilder MapGetProductsByPageEndpoint(this IEndpointR
.WithDisplayName(nameof(GetProductsByPage).Humanize())
.WithSummaryAndDescription(nameof(GetProductsByPage).Humanize(), nameof(GetProductsByPage).Humanize())
.WithTags(ProductConfigurations.Tag)
// .Produces<GetProductsByPageResponse>("Products fetched successfully.", StatusCodes.Status200OK)
// .ProducesValidationProblem("Invalid input for getting product.", StatusCodes.Status400BadRequest)
.MapToApiVersion(1.0);
// .Produces<GetProductsByPageResponse>("Products fetched successfully.", StatusCodes.Status200OK)
// .ProducesValidationProblem("Invalid input for getting product.", StatusCodes.Status400BadRequest)

async Task<Results<Ok<GetProductsByPageResponse>, ValidationProblem>> Handle(
[AsParameters] GetProductsByPageRequestParameters requestParameters
Expand Down
3 changes: 0 additions & 3 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,6 @@
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" PrivateAssets="all" Condition="$(MSBuildProjectExtension) == '.csproj'">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncFixer" PrivateAssets="all" Condition="$(MSBuildProjectExtension) == '.csproj'">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncAwaitBestPractices" PrivateAssets="all" Condition="$(MSBuildProjectExtension) == '.csproj'">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
6 changes: 2 additions & 4 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,12 @@
<PackageVersion Include="Serilog.Enrichers.Span" Version="3.1.0" />
<PackageVersion Include="Serilog.Exceptions" Version="8.4.0" />
<PackageVersion Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.Elasticsearch" Version="10.0.0" />
<PackageVersion Include="Serilog.Formatting.Elasticsearch" Version="10.0.0" />
<PackageVersion Include="Elastic.Serilog.Sinks" Version="8.11.1" />
<PackageVersion Include="Serilog.Sinks.Async" Version="2.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageVersion Include="Serilog.Sinks.Seq" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.SpectreConsole" Version="0.3.3" />
<PackageVersion Include="Serilog.Sinks.Spectre" Version="0.5.0" />
<PackageVersion Include="SerilogAnalyzer" Version="0.15.0" />
<PackageVersion Include="SerilogTimings" Version="3.1.0" />
<PackageVersion Include="Serilog.OpenTelemetry.ConsoleSink" Version="2.0.0" />
Expand All @@ -124,7 +123,6 @@
<PackageVersion Include="OpenTelemetry.Instrumentation.MassTransit" Version="1.0.0-beta.3" />
</ItemGroup>
<ItemGroup>
<PackageVersion Include="AsyncFixer" Version="1.6.0" />
<PackageVersion Include="Meziantou.Analyzer" Version="2.0.163" />
<PackageVersion Include="Roslynator.Analyzers" Version="4.12.4" />
<PackageVersion Include="Roslynator.CodeAnalysis.Analyzers" Version="4.12.4" />
Expand Down
1 change: 0 additions & 1 deletion src/Shared/EF/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ params Assembly[] assembliesToScan
sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
}
)
// https://github.com/efcore/EFCore.NamingConventions
.UseSnakeCaseNamingConvention();

// ref: https://andrewlock.net/series/using-strongly-typed-entity-ids-to-avoid-primitive-obsession/
Expand Down
19 changes: 19 additions & 0 deletions src/Shared/Logging/Enrichers/BaggageEnricher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Diagnostics;
using Serilog.Core;
using Serilog.Events;

namespace Shared.Logging.Enrichers;

public class BaggageEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (Activity.Current == null)
return;

foreach (var (key, value) in Activity.Current.Baggage)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(key, value));
}
}
}
73 changes: 73 additions & 0 deletions src/Shared/Logging/Enrichers/LogEnricher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Serilog;
using Serilog.Events;

namespace Shared.Logging.Enrichers;

// Ref: https://andrewlock.net/using-serilog-aspnetcore-in-asp-net-core-3-logging-the-selected-endpoint-name-with-serilog/
// https://andrewlock.net/using-serilog-aspnetcore-in-asp-net-core-3-excluding-health-check-endpoints-from-serilog-request-logging/
// https://github.com/serilog/serilog-aspnetcore/issues/163
public static class LogEnricher
{
/// <summary>
/// Enriches the HTTP request log with additional data via the Diagnostic Context.
/// </summary>
/// <param name="diagnosticContext">The Serilog diagnostic context.</param>
/// <param name="httpContext">The current HTTP Context.</param>
public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
{
var request = httpContext.Request;

// Set all the common properties available for every request
diagnosticContext.Set("Host", request.Host);
diagnosticContext.Set("Protocol", request.Protocol);
diagnosticContext.Set("Scheme", request.Scheme);

// Only set it if available. You're not sending sensitive data in a querystring right?!
if (request.QueryString.HasValue)
{
diagnosticContext.Set("QueryString", request.QueryString.Value);
}

// Set the content-type of the Response at this point
diagnosticContext.Set("ContentType", httpContext.Response.ContentType);

// Set userId
diagnosticContext.Set("UserId", httpContext.User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier)?.Value);

// Retrieve the IEndpointFeature selected for the request
var endpoint = httpContext.GetEndpoint();
if (endpoint is not null)
{
diagnosticContext.Set("EndpointName", endpoint.DisplayName);
}
}

/// <summary>
/// Shows request logs just in Information log level, this means we should set serilog `MinimumLevel:Default` to `Information` (for example ir doesn't show in Warning level) and shows health check logs just in `Debug` log level that is higher than Information (for getting fewer logs in the output).
/// </summary>
/// <param name="ctx"></param>
/// <param name="_"></param>
/// <param name="ex"></param>
/// <returns></returns>
public static LogEventLevel GetLogLevel(HttpContext ctx, double _, Exception? ex) =>
ex != null ? LogEventLevel.Error
: ctx.Response.StatusCode > 499 ? LogEventLevel.Error
: IsHealthCheckEndpoint(ctx) || IsSwagger(ctx) ? LogEventLevel.Debug
: LogEventLevel.Information;

private static bool IsSwagger(HttpContext ctx)
{
var isHealth = ctx.Request.Path.Value?.Contains("swagger", StringComparison.Ordinal) ?? false;

return isHealth;
}

private static bool IsHealthCheckEndpoint(HttpContext ctx)
{
var isHealth = ctx.Request.Path.Value?.Contains("health", StringComparison.Ordinal) ?? false;

return isHealth;
}
}
Loading

0 comments on commit 0c80560

Please sign in to comment.