├── .dockerignore ├── .gitignore ├── README.md ├── sample-log-monitoring.sln └── src ├── .dockerignore ├── Sample.Serilog.WebApi.Core ├── Extensions │ ├── ApiExtensions.cs │ ├── HeathCheckExtensions.cs │ ├── LogEnricherExtensions.cs │ ├── SerilogExtensions.cs │ └── SwaggerExtensions.cs ├── HealthCheck │ └── MyHealthCheck.cs ├── Middleware │ ├── ErrorHandlingMiddleware.cs │ └── RequestSerilLogMiddleware.cs └── Sample.Serilog.WebApi.Core.csproj ├── Sample.Serilog.WebApi ├── Controllers │ └── LogController.cs ├── Dockerfile ├── Program.cs ├── Properties │ └── launchSettings.json ├── Sample.Serilog.WebApi.csproj └── appsettings.json ├── docker-compose.dcproj └── docker-compose.yml /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | 20 | # Build results 21 | [Dd]ebug/ 22 | [Dd]ebugPublic/ 23 | [Rr]elease/ 24 | [Rr]eleases/ 25 | x64/ 26 | x86/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # StyleCop 66 | StyleCopReport.xml 67 | 68 | # Files built by Visual Studio 69 | *_i.c 70 | *_p.c 71 | *_h.h 72 | *.ilk 73 | *.meta 74 | *.obj 75 | *.iobj 76 | *.pch 77 | *.pdb 78 | *.ipdb 79 | *.pgc 80 | *.pgd 81 | *.rsp 82 | *.sbr 83 | *.tlb 84 | *.tli 85 | *.tlh 86 | *.tmp 87 | *.tmp_proj 88 | *_wpftmp.csproj 89 | *.log 90 | *.vspscc 91 | *.vssscc 92 | .builds 93 | *.pidb 94 | *.svclog 95 | *.scc 96 | 97 | # Chutzpah Test files 98 | _Chutzpah* 99 | 100 | # Visual C++ cache files 101 | ipch/ 102 | *.aps 103 | *.ncb 104 | *.opendb 105 | *.opensdf 106 | *.sdf 107 | *.cachefile 108 | *.VC.db 109 | *.VC.VC.opendb 110 | 111 | # Visual Studio profiler 112 | *.psess 113 | *.vsp 114 | *.vspx 115 | *.sap 116 | 117 | # Visual Studio Trace Files 118 | *.e2e 119 | 120 | # TFS 2012 Local Workspace 121 | $tf/ 122 | 123 | # Guidance Automation Toolkit 124 | *.gpState 125 | 126 | # ReSharper is a .NET coding add-in 127 | _ReSharper*/ 128 | *.[Rr]e[Ss]harper 129 | *.DotSettings.user 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # NuGet Symbol Packages 189 | *.snupkg 190 | # The packages folder can be ignored because of Package Restore 191 | **/[Pp]ackages/* 192 | # except build/, which is used as an MSBuild target. 193 | !**/[Pp]ackages/build/ 194 | # Uncomment if necessary however generally it will be regenerated when needed 195 | #!**/[Pp]ackages/repositories.config 196 | # NuGet v3's project.json files produces more ignorable files 197 | *.nuget.props 198 | *.nuget.targets 199 | 200 | # Microsoft Azure Build Output 201 | csx/ 202 | *.build.csdef 203 | 204 | # Microsoft Azure Emulator 205 | ecf/ 206 | rcf/ 207 | 208 | # Windows Store app package directories and files 209 | AppPackages/ 210 | BundleArtifacts/ 211 | Package.StoreAssociation.xml 212 | _pkginfo.txt 213 | *.appx 214 | *.appxbundle 215 | *.appxupload 216 | 217 | # Visual Studio cache files 218 | # files ending in .cache can be ignored 219 | *.[Cc]ache 220 | # but keep track of directories ending in .cache 221 | !?*.[Cc]ache/ 222 | 223 | # Others 224 | ClientBin/ 225 | ~$* 226 | *~ 227 | *.dbmdl 228 | *.dbproj.schemaview 229 | *.jfm 230 | *.pfx 231 | *.publishsettings 232 | orleans.codegen.cs 233 | 234 | # Including strong name files can present a security risk 235 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 236 | #*.snk 237 | 238 | # Since there are multiple workflows, uncomment next line to ignore bower_components 239 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 240 | #bower_components/ 241 | 242 | # RIA/Silverlight projects 243 | Generated_Code/ 244 | 245 | # Backup & report files from converting an old project file 246 | # to a newer Visual Studio version. Backup files are not needed, 247 | # because we have git ;-) 248 | _UpgradeReport_Files/ 249 | Backup*/ 250 | UpgradeLog*.XML 251 | UpgradeLog*.htm 252 | ServiceFabricBackup/ 253 | *.rptproj.bak 254 | 255 | # SQL Server files 256 | *.mdf 257 | *.ldf 258 | *.ndf 259 | 260 | # Business Intelligence projects 261 | *.rdl.data 262 | *.bim.layout 263 | *.bim_*.settings 264 | *.rptproj.rsuser 265 | *- [Bb]ackup.rdl 266 | *- [Bb]ackup ([0-9]).rdl 267 | *- [Bb]ackup ([0-9][0-9]).rdl 268 | 269 | # Microsoft Fakes 270 | FakesAssemblies/ 271 | 272 | # GhostDoc plugin setting file 273 | *.GhostDoc.xml 274 | 275 | # Node.js Tools for Visual Studio 276 | .ntvs_analysis.dat 277 | node_modules/ 278 | 279 | # Visual Studio 6 build log 280 | *.plg 281 | 282 | # Visual Studio 6 workspace options file 283 | *.opt 284 | 285 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 286 | *.vbw 287 | 288 | # Visual Studio LightSwitch build output 289 | **/*.HTMLClient/GeneratedArtifacts 290 | **/*.DesktopClient/GeneratedArtifacts 291 | **/*.DesktopClient/ModelManifest.xml 292 | **/*.Server/GeneratedArtifacts 293 | **/*.Server/ModelManifest.xml 294 | _Pvt_Extensions 295 | 296 | # Paket dependency manager 297 | .paket/paket.exe 298 | paket-files/ 299 | 300 | # FAKE - F# Make 301 | .fake/ 302 | 303 | # CodeRush personal settings 304 | .cr/personal 305 | 306 | # Python Tools for Visual Studio (PTVS) 307 | __pycache__/ 308 | *.pyc 309 | 310 | # Cake - Uncomment if you are using it 311 | # tools/** 312 | # !tools/packages.config 313 | 314 | # Tabs Studio 315 | *.tss 316 | 317 | # Telerik's JustMock configuration file 318 | *.jmconfig 319 | 320 | # BizTalk build output 321 | *.btp.cs 322 | *.btm.cs 323 | *.odx.cs 324 | *.xsd.cs 325 | 326 | # OpenCover UI analysis results 327 | OpenCover/ 328 | 329 | # Azure Stream Analytics local run output 330 | ASALocalRun/ 331 | 332 | # MSBuild Binary and Structured Log 333 | *.binlog 334 | 335 | # NVidia Nsight GPU debugger configuration file 336 | *.nvuser 337 | 338 | # MFractors (Xamarin productivity tool) working folder 339 | .mfractor/ 340 | 341 | # Local History for Visual Studio 342 | .localhistory/ 343 | 344 | # BeatPulse healthcheck temp database 345 | healthchecksdb 346 | 347 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 348 | MigrationBackup/ 349 | 350 | # Ionide (cross platform F# VS Code tools) working folder 351 | .ionide/ 352 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .NET 7 Logging and Monitoring Example 2 | 3 | - .NET 7.0 4 | - Health Check 5 | - Health Check UI 6 | - Serilog 7 | - Swashbuckle Swagger 8 | - Middlewares 9 | 10 | https://henriquemauri.net/melhores-pr-ticas-de-monitoramento-no-net-core-3-1-442f03b71d74/ 11 | -------------------------------------------------------------------------------- /sample-log-monitoring.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30105.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample.Serilog.WebApi", "src\Sample.Serilog.WebApi\Sample.Serilog.WebApi.csproj", "{2CAF22E2-6510-4B11-8F5F-89E0A3C05010}" 7 | EndProject 8 | Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "src\docker-compose.dcproj", "{18F6D3A5-091F-4A10-B5BC-57E2239C80D6}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Presentation", "Presentation", "{1F4C7FFA-7156-4355-A604-34293A63EDB1}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample.Serilog.WebApi.Core", "src\Sample.Serilog.WebApi.Core\Sample.Serilog.WebApi.Core.csproj", "{EAE3FF16-13E9-42CA-93B7-43660C14A7A1}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {2CAF22E2-6510-4B11-8F5F-89E0A3C05010}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {2CAF22E2-6510-4B11-8F5F-89E0A3C05010}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {2CAF22E2-6510-4B11-8F5F-89E0A3C05010}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {2CAF22E2-6510-4B11-8F5F-89E0A3C05010}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {18F6D3A5-091F-4A10-B5BC-57E2239C80D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {18F6D3A5-091F-4A10-B5BC-57E2239C80D6}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {18F6D3A5-091F-4A10-B5BC-57E2239C80D6}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {18F6D3A5-091F-4A10-B5BC-57E2239C80D6}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {EAE3FF16-13E9-42CA-93B7-43660C14A7A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {EAE3FF16-13E9-42CA-93B7-43660C14A7A1}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {EAE3FF16-13E9-42CA-93B7-43660C14A7A1}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {EAE3FF16-13E9-42CA-93B7-43660C14A7A1}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(NestedProjects) = preSolution 37 | {2CAF22E2-6510-4B11-8F5F-89E0A3C05010} = {1F4C7FFA-7156-4355-A604-34293A63EDB1} 38 | {EAE3FF16-13E9-42CA-93B7-43660C14A7A1} = {1F4C7FFA-7156-4355-A604-34293A63EDB1} 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {EED24293-FCEB-4257-A890-7B61D64A99FE} 42 | EndGlobalSection 43 | EndGlobal 44 | 45 | -------------------------------------------------------------------------------- /src/.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Extensions/ApiExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Sample.Serilog.WebApi.Core.HealthCheck; 6 | using Sample.Serilog.WebApi.Core.Middleware; 7 | using Serilog; 8 | 9 | namespace Sample.Serilog.WebApi.Core.Extensions; 10 | public static class ApiConfigurationExtensions 11 | { 12 | public static void AddApiConfiguration(this IServiceCollection services) 13 | { 14 | services.AddRouting(options => options.LowercaseUrls = true); 15 | 16 | services.AddScoped(); 17 | 18 | services.AddHttpClient(); 19 | services.AddControllers(); 20 | } 21 | 22 | public static void UseApiConfiguration(this IApplicationBuilder app, IWebHostEnvironment env) 23 | { 24 | if (env.IsDevelopment()) 25 | { 26 | app.UseDeveloperExceptionPage(); 27 | } 28 | 29 | app.UseSerilogRequestLogging(opts => opts.EnrichDiagnosticContext = LogEnricherExtensions.EnrichFromRequest); 30 | 31 | app.UseMiddleware(); 32 | app.UseMiddleware(); 33 | 34 | app.UseHttpsRedirection(); 35 | app.UseRouting(); 36 | } 37 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Extensions/HeathCheckExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Diagnostics.HealthChecks; 6 | using Sample.Serilog.WebApi.Core.HealthCheck; 7 | 8 | namespace Sample.Serilog.WebApi.Core.Extensions; 9 | 10 | public static class HeathCheckExtensions 11 | { 12 | public static void AddHeathCheckApi(this IServiceCollection services, IConfiguration configuration) 13 | { 14 | services.AddHealthChecks() 15 | .AddCheck("Situação", () => HealthCheckResult.Unhealthy()) 16 | .AddCheck("Dependências") 17 | .AddSqlServer( 18 | configuration.GetConnectionString("DefaultConnection"), "SELECT 1;", "Sql Server", HealthStatus.Degraded, timeout: TimeSpan.FromSeconds(30), tags: new[] { "db", "sql", "sqlServer", }) 19 | .AddRedis( 20 | configuration.GetConnectionString("RedisConnection"), "Redis", HealthStatus.Degraded, new[] { "redis", "cache" }) 21 | .AddElasticsearch( 22 | configuration.GetConnectionString("Elasticsearch"), "ElasticSearch", HealthStatus.Degraded, new[] { "elastic", "search" }); 23 | 24 | services.AddHealthChecksUI(config => 25 | { 26 | config.SetEvaluationTimeInSeconds(5); 27 | config.AddHealthCheckEndpoint("Host Externo", ObterHostNameApiHealthCheck()); 28 | config.AddHealthCheckEndpoint("Aplicação", $"http://localhost:5001/hc"); 29 | 30 | config.AddWebhookNotification("Slack Notification WebHook", "Your_Slack_WebHook_Uri_Goes_Here", 31 | "{\"text\": \"[[LIVENESS]] is failing with the error message : [[FAILURE]]\"}", 32 | "{\"text\": \"[[LIVENESS]] is recovered.All is up & running !\"}"); 33 | 34 | }).AddInMemoryStorage(); 35 | } 36 | 37 | public static void UseHealthCheckApi(this IApplicationBuilder app) 38 | { 39 | app.UseHealthChecksUI(config => 40 | { 41 | config.UIPath = "/hc-ui"; 42 | }); 43 | } 44 | 45 | public static string ObterHostNameApiHealthCheck() 46 | { 47 | var tt = Environment.GetEnvironmentVariable("HostNameHealthCheck") == null ? "/api/hc" : $"{Environment.GetEnvironmentVariable("HostNameHealthCheck")}/api/hc"; 48 | return tt; 49 | } 50 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Extensions/LogEnricherExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Http.Features; 3 | using Microsoft.AspNetCore.Routing; 4 | using Serilog; 5 | using System; 6 | using System.Linq; 7 | 8 | namespace Sample.Serilog.WebApi.Core.Extensions; 9 | 10 | public static class LogEnricherExtensions 11 | { 12 | public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext) 13 | { 14 | diagnosticContext.Set("UserName", httpContext?.User?.Identity?.Name); 15 | diagnosticContext.Set("ClientIP", httpContext.Connection.RemoteIpAddress.ToString()); 16 | diagnosticContext.Set("UserAgent", httpContext.Request.Headers["User-Agent"].FirstOrDefault()); 17 | diagnosticContext.Set("Resource", httpContext.GetMetricsCurrentResourceName()); 18 | } 19 | 20 | public static string GetMetricsCurrentResourceName(this HttpContext httpContext) 21 | { 22 | if (httpContext == null) 23 | throw new ArgumentNullException(nameof(httpContext)); 24 | 25 | Endpoint endpoint = httpContext.Features.Get()?.Endpoint; 26 | 27 | return endpoint?.Metadata.GetMetadata()?.EndpointName; 28 | } 29 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Extensions/SerilogExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.ApplicationInsights.Extensibility; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.Logging; 6 | using Serilog; 7 | using Serilog.Filters; 8 | using Serilog.Sinks.Elasticsearch; 9 | 10 | namespace Sample.Serilog.WebApi.Core.Extensions; 11 | 12 | public static class SerilogExtensions 13 | { 14 | public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builder, IConfiguration configuration, string applicationName) 15 | { 16 | Log.Logger = new LoggerConfiguration() 17 | .ReadFrom.Configuration(configuration) 18 | .Enrich.WithProperty("ApplicationName", $"{applicationName} - {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}") 19 | .Enrich.FromLogContext() 20 | .Enrich.WithMachineName() 21 | .Enrich.WithEnvironmentUserName() 22 | .Enrich.WithDemystifiedStackTraces() 23 | .Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.StaticFiles")) 24 | .Filter.ByExcluding(z => z.MessageTemplate.Text.Contains("erro de negócio")) 25 | .WriteTo.Async(writeTo => writeTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(configuration["ElasticsearchSettings:uri"])) 26 | { 27 | AutoRegisterTemplate = true, 28 | IndexFormat = "logs", 29 | ModifyConnectionSettings = x => x.BasicAuthentication(configuration["ElasticsearchSettings:username"], 30 | configuration["ElasticsearchSettings:password"]) 31 | })) 32 | .WriteTo.Async(writeTo => writeTo.Seq(configuration["Seq:uri"])) 33 | .WriteTo.Async(writeTo => writeTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces)) 34 | .WriteTo.Async(writeTo => writeTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")) 35 | .CreateLogger(); 36 | 37 | builder.Logging.ClearProviders(); 38 | builder.Host.UseSerilog(Log.Logger, true); 39 | 40 | return builder; 41 | } 42 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Extensions/SwaggerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.OpenApi.Models; 6 | 7 | namespace Sample.Serilog.WebApi.Core.Extensions; 8 | 9 | public static class SwaggerExtensions 10 | { 11 | public static void AddSwaggerApi(this IServiceCollection services, IConfiguration configuration) 12 | { 13 | services.AddSwaggerGen(c => 14 | { 15 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "Sample Logs", Version = "v1" }); 16 | c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); 17 | }); 18 | } 19 | 20 | public static void UseSwaggerDocApi(this IApplicationBuilder app) 21 | { 22 | app.UseSwagger(); 23 | app.UseSwaggerUI(c => 24 | { 25 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sample Logs"); 26 | c.RoutePrefix = "swagger"; 27 | }); 28 | } 29 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/HealthCheck/MyHealthCheck.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.Extensions.Diagnostics.HealthChecks; 5 | 6 | namespace Sample.Serilog.WebApi.Core.HealthCheck; 7 | 8 | public class MyHealthCheck : IHealthCheck 9 | { 10 | private readonly IMyCustomService dependency; 11 | 12 | public MyHealthCheck(IMyCustomService dependency) 13 | { 14 | this.dependency = dependency; 15 | } 16 | 17 | public Task CheckHealthAsync(HealthCheckContext context,CancellationToken cancellationToken = default(CancellationToken)) 18 | { 19 | var result = dependency.IsHealthy() ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy("Erro ao carregar as dependências."); 20 | return Task.FromResult(result); 21 | } 22 | } 23 | 24 | public interface IMyCustomService 25 | { 26 | public bool IsHealthy(); 27 | } 28 | 29 | public class MyCustomService : IMyCustomService 30 | { 31 | public bool IsHealthy() 32 | { 33 | return new Random().NextDouble() > 0.6; 34 | } 35 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Middleware/ErrorHandlingMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Threading.Tasks; 4 | using Microsoft.AspNetCore.Http; 5 | using Newtonsoft.Json; 6 | using Serilog; 7 | 8 | namespace Sample.Serilog.WebApi.Core.Middleware; 9 | 10 | public class ErrorHandlingMiddleware 11 | { 12 | private readonly RequestDelegate next; 13 | 14 | public ErrorHandlingMiddleware(RequestDelegate next) 15 | { 16 | this.next = next; 17 | } 18 | 19 | public async Task Invoke(HttpContext context) 20 | { 21 | try 22 | { 23 | await next(context); 24 | } 25 | catch (Exception ex) 26 | { 27 | await HandleExceptionAsync(context, ex); 28 | } 29 | } 30 | 31 | private static Task HandleExceptionAsync(HttpContext context, Exception exception) 32 | { 33 | Log.Error(exception, "Erro não tratado"); 34 | 35 | var code = HttpStatusCode.InternalServerError; 36 | 37 | if (exception is Exception) code = HttpStatusCode.BadRequest; 38 | // else if (exception is MyUnauthorizedException) code = HttpStatusCode.Unauthorized; 39 | // else if (exception is MyException) code = HttpStatusCode.BadRequest; 40 | 41 | var result = JsonConvert.SerializeObject(new { error = exception.Message }); 42 | 43 | context.Response.ContentType = "application/json"; 44 | context.Response.StatusCode = (int)code; 45 | return context.Response.WriteAsync(result); 46 | } 47 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Middleware/RequestSerilLogMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.Extensions.Primitives; 3 | using Serilog.Context; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Sample.Serilog.WebApi.Core.Middleware; 8 | 9 | public class RequestSerilLogMiddleware 10 | { 11 | private readonly RequestDelegate _next; 12 | 13 | public RequestSerilLogMiddleware(RequestDelegate next) 14 | { 15 | _next = next; 16 | } 17 | 18 | public Task Invoke(HttpContext context) 19 | { 20 | using (LogContext.PushProperty("UserName", context?.User?.Identity?.Name ?? "anônimo")) 21 | using (LogContext.PushProperty("CorrelationId", GetCorrelationId(context))) 22 | { 23 | return _next.Invoke(context); 24 | } 25 | } 26 | 27 | private string GetCorrelationId(HttpContext httpContext) 28 | { 29 | httpContext.Request.Headers.TryGetValue("Cko-Correlation-Id", out StringValues correlationId); 30 | return correlationId.FirstOrDefault() ?? httpContext.TraceIdentifier; 31 | } 32 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi.Core/Sample.Serilog.WebApi.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/Controllers/LogController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System; 3 | using System.Net.Http; 4 | using System.Threading.Tasks; 5 | 6 | namespace Sample.Serilog.WebApi.Controllers; 7 | 8 | [Route("api/[controller]")] 9 | public class LogController : Controller 10 | { 11 | private readonly IHttpClientFactory _httpClientFactory; 12 | 13 | public LogController(IHttpClientFactory httpClientFactory) 14 | { 15 | _httpClientFactory = httpClientFactory; 16 | } 17 | 18 | [HttpPost("sample")] 19 | public IActionResult PostSampleData() 20 | { 21 | return Ok(new { Result = "Data successfully registered with Elasticsearch" }); 22 | } 23 | 24 | [HttpGet("exception")] 25 | public IActionResult GetByName() 26 | { 27 | //Sample middlerare exception log 28 | throw new Exception("Não foi possível fazer o get."); 29 | } 30 | 31 | [HttpGet("cidades")] 32 | public async Task GetCitiesAsync() 33 | { 34 | var result = string.Empty; 35 | var client = _httpClientFactory.CreateClient(); 36 | var response = await client.GetAsync("https://servicodados.ibge.gov.br/api/v1/localidades/estados/ES/municipios"); 37 | 38 | if (response.IsSuccessStatusCode) 39 | { 40 | result = await response.Content.ReadAsStringAsync(); 41 | } 42 | 43 | return Ok(result); 44 | } 45 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | EXPOSE 443 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build 9 | WORKDIR /src 10 | COPY ["src/Sample.Serilog.WebApi/Sample.Serilog.WebApi.csproj", "src/Sample.Serilog.WebApi/"] 11 | COPY ["src/Sample.Serilog.WebApi.Core/Sample.Serilog.WebApi.Core.csproj", "src/Sample.Serilog.WebApi.Core/"] 12 | RUN dotnet restore "src/Sample.Serilog.WebApi/Sample.Serilog.WebApi.csproj" 13 | COPY . . 14 | WORKDIR "/src/src/Sample.Serilog.WebApi" 15 | RUN dotnet build "Sample.Serilog.WebApi.csproj" -c Release -o /app/build 16 | 17 | FROM build AS publish 18 | RUN dotnet publish "Sample.Serilog.WebApi.csproj" -c Release -o /app/publish 19 | 20 | FROM base AS final 21 | WORKDIR /app 22 | COPY --from=publish /app/publish . 23 | ENTRYPOINT ["dotnet", "Sample.Serilog.WebApi.dll"] -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using HealthChecks.UI.Client; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Diagnostics.HealthChecks; 5 | using Sample.Serilog.WebApi.Core.Extensions; 6 | using Serilog; 7 | 8 | try 9 | { 10 | var builder = WebApplication.CreateBuilder(args); 11 | builder.AddSerilog(builder.Configuration, "API Exemplo"); 12 | Log.Information("Getting the motors running..."); 13 | 14 | builder.Services.AddApiConfiguration(); 15 | builder.Services.AddSwaggerApi(builder.Configuration); 16 | builder.Services.AddHeathCheckApi(builder.Configuration); 17 | 18 | var app = builder.Build(); 19 | 20 | app.UseApiConfiguration(app.Environment); 21 | 22 | app.UseSwaggerDocApi(); 23 | app.UseHealthCheckApi(); 24 | 25 | app.UseEndpoints(endpoints => 26 | { 27 | endpoints.MapControllers(); 28 | endpoints.MapHealthChecks("/hc", 29 | new HealthCheckOptions 30 | { 31 | Predicate = _ => true, 32 | ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse, 33 | }); 34 | }); 35 | 36 | app.Run(); 37 | } 38 | catch (Exception ex) 39 | { 40 | Log.Fatal(ex, "Host terminated unexpectedly"); 41 | } 42 | finally 43 | { 44 | Log.Information("Server Shutting down..."); 45 | Log.CloseAndFlush(); 46 | } 47 | -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:65025", 7 | "sslPort": 44378 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Sample.Serilog.WebApi": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "swagger", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "applicationUrl": "http://localhost:5001" 28 | }, 29 | "Docker": { 30 | "commandName": "Docker", 31 | "launchBrowser": true, 32 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", 33 | "publishAllPorts": true, 34 | "useSSL": true 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/Sample.Serilog.WebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | Sample.Serilog.WebApi 6 | ff15173f-95e1-4a96-978d-e65678b218b9 7 | Linux 8 | ..\docker-compose.dcproj 9 | ..\.. 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Sample.Serilog.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "ConnectionStrings": { 10 | "DefaultConnection": "xxxxxxxxx.xxx", 11 | "RedisConnection": "xxxxxxxxx.xxx", 12 | "RabbitMQ": "xxxxxxxxx.xxx", 13 | "Elasticsearch": "xxxxxxxxx.xxx" 14 | }, 15 | "ElasticsearchSettings": { 16 | "uri": "http://localhost:9200", 17 | "defaultIndex": "indexlogs", 18 | "username": "elastic", 19 | "password": "MagicWord" 20 | }, 21 | "Seq": { 22 | "uri": "http://localhost:5341" 23 | }, 24 | "APPINSIGHTS_INSTRUMENTATIONKEY": "11111111111111", 25 | "AllowedHosts": "*" 26 | } 27 | -------------------------------------------------------------------------------- /src/docker-compose.dcproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 2.1 5 | Linux 6 | 18f6d3a5-091f-4a10-b5bc-57e2239c80d6 7 | LaunchBrowser 8 | {Scheme}://localhost:{ServicePort}/weatherforecast 9 | sample-elasticsearch 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | seq: 5 | container_name: seq 6 | image: datalust/seq:latest 7 | ports: 8 | - 80:80 9 | - 5341:5341 10 | environment: 11 | - ACCEPT_EULA=Y 12 | 13 | elasticsearch: 14 | container_name: elasticsearch 15 | image: docker.elastic.co/elasticsearch/elasticsearch:7.8.0 16 | ports: 17 | - 9200:9200 18 | volumes: 19 | - elasticsearch-data:/usr/share/elasticsearch/data 20 | environment: 21 | - xpack.monitoring.enabled=true 22 | - xpack.watcher.enabled=false 23 | - "ES_JAVA_OPTS=-Xms512m -Xmx512m" 24 | - discovery.type=single-node 25 | - ELASTICSEARCH_USERNAME=elastic 26 | - ELASTICSEARCH_PASSWORD=MagicWord 27 | networks: 28 | - elastic 29 | 30 | kibana: 31 | container_name: kibana 32 | image: docker.elastic.co/kibana/kibana:7.8.0 33 | ports: 34 | - 5601:5601 35 | depends_on: 36 | - elasticsearch 37 | environment: 38 | - ELASTICSEARCH_URL=http://localhost:9200 39 | - ELASTICSEARCH_USERNAME=elastic 40 | - ELASTICSEARCH_PASSWORD=MagicWord 41 | networks: 42 | - elastic 43 | 44 | networks: 45 | elastic: 46 | driver: bridge 47 | 48 | volumes: 49 | elasticsearch-data: --------------------------------------------------------------------------------