├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── .travis.yml ├── AspNetCoreMsLoggerExample.Web ├── AspNetCoreMsLoggerExample.Web.csproj ├── Program.cs ├── appsettings.Development.json └── appsettings.json ├── AspNetCoreSerilogExample.Web ├── AspNetCoreSerilogExample.Web.csproj ├── Controllers │ └── TestController.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── AspNetCoreSerilogExample.sln ├── AspNetCoreSerilogExample.sln.startup.json └── README.md /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a .NET project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net 3 | 4 | name: .NET 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v3 21 | with: 22 | dotnet-version: 6.0.x 23 | - name: Restore dependencies 24 | run: dotnet restore 25 | - name: Build 26 | run: dotnet build --no-restore 27 | -------------------------------------------------------------------------------- /.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 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | mono: none 3 | sudo: required 4 | dist: xenial 5 | dotnet: 5.0 6 | script: 7 | - dotnet restore 8 | - dotnet build AspNetCoreSerilogExample.sln -c Release 9 | global: 10 | - DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true 11 | - DOTNET_CLI_TELEMETRY_OPTOUT=1 12 | -------------------------------------------------------------------------------- /AspNetCoreMsLoggerExample.Web/AspNetCoreMsLoggerExample.Web.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /AspNetCoreMsLoggerExample.Web/Program.cs: -------------------------------------------------------------------------------- 1 | // Logging based on https://github.com/jernejk/AspNetCoreSerilogExample 2 | // NOTE: When upgrading from .NET 5 or earlier, add `enable` to **.csproj** file under ``. 3 | // NOTE: You can still use full Program.cs and Startup.cs if you want to and it's similar to .NET 5. 4 | 5 | try 6 | { 7 | var builder = WebApplication.CreateBuilder(args); 8 | 9 | // Register required services. 10 | builder.Services.AddControllers(); 11 | builder.Services.AddLogging(loggingBuilder => 12 | { 13 | // NOTE: You can add more log providers here. 14 | #if DEBUG 15 | // Add Seq for local dev. 16 | loggingBuilder.AddSeq(); 17 | #endif 18 | }); 19 | 20 | WebApplication app = builder.Build(); 21 | 22 | // Configuration. 23 | if (app.Environment.IsDevelopment()) 24 | { 25 | app.UseDeveloperExceptionPage(); 26 | } 27 | 28 | // NOTE: If you need UseAuthentication/UseAuthorization, use it after `UseRouting` and before `UseEndpoints`. 29 | app.UseRouting(); 30 | app.UseEndpoints(endpoints => 31 | { 32 | endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}"); 33 | endpoints.MapGet("", context => context.Response.WriteAsync("Hello World!\nUse /api/test/flatlog?input=Test, /api/test/StructuredLog?input=Test, etc. and observe console/Seq for logs.")); 34 | }); 35 | 36 | app.Run(); 37 | } 38 | catch (Exception ex) 39 | { 40 | // Loading configuration or running the application failed. 41 | // This will create a logger that can be captured by Azure logger. 42 | // To enable Azure logger, in Azure Portal: 43 | // 1. Go to WebApp 44 | // 2. App Service logs 45 | // 3. Enable "Application Logging (Filesystem)", "Application Logging (Filesystem)" and "Detailed error messages" 46 | // 4. Set Retention Period (Days) to 10 or similar value 47 | // 5. Save settings 48 | // 6. Under Overview, restart web app 49 | // 7. Go to Log Stream and observe the logs 50 | Console.WriteLine("Host terminated unexpectedly: " + ex); 51 | } 52 | -------------------------------------------------------------------------------- /AspNetCoreMsLoggerExample.Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "DetailedErrors": true, 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Information", 6 | "Microsoft": "Warning", 7 | "Microsoft.Hosting.Lifetime": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /AspNetCoreMsLoggerExample.Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "System": "Information", 6 | "Microsoft": "Information", 7 | "Microsoft.EntityFrameworkCore": "Information" 8 | } 9 | }, 10 | "AllowedHosts": "*" 11 | } 12 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/AspNetCoreSerilogExample.Web.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | PreserveNewest 25 | Always 26 | 27 | 28 | PreserveNewest 29 | Never 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/Controllers/TestController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Diagnostics; 3 | 4 | namespace AspNetCoreSerilogExample.Web.Controllers; 5 | 6 | // NOTE: TestController is the same for MS Logger as well as Serilog by design. 7 | // You can use exactly the same logging for both and only difference is how you configure the 2 loggers. 8 | [Route("api/[controller]/[action]")] 9 | [ApiController] 10 | public class TestController : ControllerBase 11 | { 12 | private readonly ILogger _logger; 13 | 14 | public TestController(ILogger logger) 15 | { 16 | _logger = logger; 17 | } 18 | 19 | [HttpGet] 20 | public void FlatLog(string input) 21 | { 22 | // NOTE: Don't use flat logs! Use structured logs. (example below) 23 | _logger.LogInformation($"Input text: {input}"); 24 | } 25 | 26 | [HttpGet] 27 | public void StructuredLog(string input) 28 | { 29 | _logger.LogInformation("Input text: {Input}", input); 30 | } 31 | 32 | [HttpGet] 33 | public void EnrichLog(string input, string inputType) 34 | { 35 | _logger.LogInformation("Input text: {Input} with {InputType}", input, inputType); 36 | } 37 | 38 | [HttpGet] 39 | public void ScopeLog(string input, string additionalContext) 40 | { 41 | // Variable _ is discarded and this scope lasts until the end of the method. 42 | // You can still use using with curly brackets as before if you need it to limit scope or readability preference. 43 | // There a few utils that can simplify the code: https://github.com/jernejk/EfCoreSamples.Logging/blob/master/EfCoreSamples.Logging.Persistence/Utils/LoggingExtensions.cs 44 | using var _ = _logger.BeginScope(new Dictionary { { "AdditionalContext", additionalContext } }); 45 | 46 | _logger.LogInformation("Input text with scope: {Input}", input); 47 | 48 | MoreWork(); 49 | } 50 | 51 | [HttpGet] 52 | public async Task TimeLog() 53 | { 54 | Stopwatch stopwatch = Stopwatch.StartNew(); 55 | await Task.Delay(new Random().Next(2000)); 56 | stopwatch.Stop(); 57 | 58 | _logger.LogInformation("Long task: {LongTimeElapsedMs}ms", stopwatch.ElapsedMilliseconds); 59 | } 60 | 61 | private void MoreWork() 62 | { 63 | // This will have additional properties in the structured log if called inside a log context. 64 | _logger.LogInformation("More logs"); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/Program.cs: -------------------------------------------------------------------------------- 1 | // Logging based on https://github.com/jernejk/AspNetCoreSerilogExample and https://github.com/datalust/dotnet6-serilog-example 2 | // NOTE: When upgrading from .NET 5 or earlier, add `enable` to **.csproj** file under ``. 3 | // NOTE: While you can still use full Program.cs and Startup.cs, `.UseSerilog()` is marked as obsolete for them. It's safer to move to minimal APIs. 4 | using Serilog; 5 | using System.Diagnostics; 6 | 7 | try 8 | { 9 | var builder = WebApplication.CreateBuilder(args); 10 | 11 | builder.Host.UseSerilog((ctx, loggerConfiguration) => 12 | { 13 | loggerConfiguration 14 | .ReadFrom.Configuration(ctx.Configuration) 15 | .Enrich.FromLogContext() 16 | .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) 17 | .Enrich.WithProperty("Environment", ctx.HostingEnvironment); 18 | 19 | #if DEBUG 20 | // Used to filter out potentially bad data due debugging. 21 | // Very useful when doing Seq dashboards and want to remove logs under debugging session. 22 | loggerConfiguration.Enrich.WithProperty("DebuggerAttached", Debugger.IsAttached); 23 | #endif 24 | }); 25 | 26 | // Register services 27 | builder.Services.AddControllers(); 28 | builder.Services.AddLogging(); 29 | 30 | 31 | WebApplication app = builder.Build(); 32 | 33 | // Rest of configuration. 34 | if (app.Environment.IsDevelopment()) 35 | { 36 | app.UseDeveloperExceptionPage(); 37 | } 38 | 39 | // This will make the HTTP requests log as rich logs instead of plain text. 40 | app.UseSerilogRequestLogging(); 41 | 42 | app.UseRouting(); 43 | 44 | // Absolute minimum setup, just return "Hello world!" to browser. 45 | // You can use Controllers, SPA routing, SignalR, etc. routing. 46 | app.UseEndpoints(endpoints => 47 | { 48 | endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}"); 49 | endpoints.MapGet("", context => context.Response.WriteAsync("Hello World!\nUse /api/test/flatlog?input=Test, /api/test/StructuredLog?input=Test, etc. and observe console/Seq for logs.")); 50 | }); 51 | 52 | app.Run(); 53 | } 54 | catch (Exception ex) 55 | { 56 | if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger") 57 | { 58 | // Loading configuration or Serilog failed. 59 | // This will create a logger that can be captured by Azure logger. 60 | // To enable Azure logger, in Azure Portal: 61 | // 1. Go to WebApp 62 | // 2. App Service logs 63 | // 3. Enable "Application Logging (Filesystem)", "Application Logging (Filesystem)" and "Detailed error messages" 64 | // 4. Set Retention Period (Days) to 10 or similar value 65 | // 5. Save settings 66 | // 6. Under Overview, restart web app 67 | // 7. Go to Log Stream and observe the logs 68 | Log.Logger = new LoggerConfiguration() 69 | .MinimumLevel.Debug() 70 | .WriteTo.Console() 71 | .CreateLogger(); 72 | } 73 | 74 | Log.Fatal(ex, "Host terminated unexpectedly"); 75 | } 76 | finally 77 | { 78 | Log.Information("Shut down complete"); 79 | Log.CloseAndFlush(); 80 | } 81 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "AspNetCoreSerilogExample.Web": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "environmentVariables": { 7 | "ASPNETCORE_ENVIRONMENT": "Development" 8 | }, 9 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Serilog; 8 | 9 | namespace AspNetCoreSerilogExample.Web 10 | { 11 | public class Startup 12 | { 13 | public Startup(IConfiguration configuration) 14 | { 15 | Configuration = configuration; 16 | } 17 | 18 | public IConfiguration Configuration { get; } 19 | 20 | // This method gets called by the runtime. Use this method to add services to the container. 21 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddControllers(); 25 | services.AddLogging(); 26 | } 27 | 28 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 29 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 30 | { 31 | if (env.IsDevelopment()) 32 | { 33 | app.UseDeveloperExceptionPage(); 34 | } 35 | 36 | // This will make the HTTP requests log as rich logs instead of plain text. 37 | app.UseSerilogRequestLogging(); 38 | 39 | app.UseRouting(); 40 | 41 | // Absolute minimum setup, just return "Hello world!" to browser. 42 | // You can use Controllers, SPA routing, SignalR, etc. routing. 43 | app.UseEndpoints(endpoints => 44 | { 45 | endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}"); 46 | endpoints.MapGet("", context => context.Response.WriteAsync("Hello World!")); 47 | }); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Serilog": { 3 | "Using": [ "Serilog.Exceptions", "Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.Seq" ], 4 | "MinimumLevel": { 5 | "Default": "Verbose", 6 | "Override": { 7 | "System": "Information", 8 | "Microsoft": "Information", 9 | "Microsoft.EntityFrameworkCore": "Information" 10 | } 11 | }, 12 | "WriteTo": [ 13 | { 14 | "Name": "Seq", 15 | "Args": { 16 | "serverUrl": "http://localhost:5341", 17 | "apiKey": "none", 18 | "restrictedToMinimumLevel": "Verbose" 19 | } 20 | }, 21 | { 22 | "Name": "Async", 23 | "Args": { 24 | "configure": [ 25 | { 26 | "Name": "Console", 27 | "Args": { 28 | "restrictedToMinimumLevel": "Information" 29 | } 30 | } 31 | ] 32 | } 33 | } 34 | ], 35 | "Enrich": [ "FromLogContext", "WithExceptionDetails" ], 36 | "Properties": { 37 | "Environment": "LocalDev" 38 | } 39 | }, 40 | "Logging": { 41 | "LogLevel": { 42 | "Default": "Warning" 43 | } 44 | }, 45 | "AllowedHosts": "*" 46 | } 47 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33414.496 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreSerilogExample.Web", "AspNetCoreSerilogExample.Web\AspNetCoreSerilogExample.Web.csproj", "{BE382D81-8A74-4167-A7AD-C7FE1DD89C72}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Root", "Root", "{55156C52-24F7-4C9D-935A-4BCD2AEA6CF0}" 9 | ProjectSection(SolutionItems) = preProject 10 | .gitignore = .gitignore 11 | README.md = README.md 12 | EndProjectSection 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreMsLoggerExample.Web", "AspNetCoreMsLoggerExample.Web\AspNetCoreMsLoggerExample.Web.csproj", "{37AFFF56-53EC-4DE4-9246-1D210CB32CEC}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {BE382D81-8A74-4167-A7AD-C7FE1DD89C72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {BE382D81-8A74-4167-A7AD-C7FE1DD89C72}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {BE382D81-8A74-4167-A7AD-C7FE1DD89C72}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {BE382D81-8A74-4167-A7AD-C7FE1DD89C72}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {37AFFF56-53EC-4DE4-9246-1D210CB32CEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {37AFFF56-53EC-4DE4-9246-1D210CB32CEC}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {37AFFF56-53EC-4DE4-9246-1D210CB32CEC}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {37AFFF56-53EC-4DE4-9246-1D210CB32CEC}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {296EF11D-A826-4D2A-9A98-2025ACDD5BC8} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /AspNetCoreSerilogExample.sln.startup.json: -------------------------------------------------------------------------------- 1 | /* 2 | This is a configuration file for the SwitchStartupProject Visual Studio Extension 3 | See https://heptapod.host/thirteen/switchstartupproject/blob/branch/current/Configuration.md 4 | */ 5 | { 6 | /* Configuration File Version */ 7 | "Version": 3, 8 | 9 | /* Create an item in the dropdown list for each project in the solution? */ 10 | "ListAllProjects": true, 11 | "MultiProjectConfigurations": { 12 | "Both": { 13 | "Projects": { 14 | "AspNetCoreMsLoggerExample.Web": {}, 15 | "AspNetCoreSerilogExample.Web": {} 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ASP.NET Core 6.0 Serilog Template 2 | 3 | This is an example of how to create a ASP .NET Core app with Serilog (.NET 7+) 4 | 5 | Check my blog post for more details: [ASP.NET Core + Serilog](https://jkdev.me/asp-net-core-serilog/) 6 | 7 | If you're looking for .NET (Core) versions, checkout the old branches: https://github.com/jernejk/AspNetCoreSerilogExample/branches 8 | 9 | ## 1. Add Nuget packages 10 | 11 | In `csproj` add: 12 | 13 | ``` xml 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | PreserveNewest 32 | Always 33 | 34 | 35 | PreserveNewest 36 | Never 37 | 38 | 39 | ``` 40 | 41 | ## 2. Add Serilog configuration 42 | 43 | Add Seq and async console configuration in `appsetings.json`: 44 | 45 | ``` js 46 | "Serilog": { 47 | "Using": [ "Serilog.Exceptions", "Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.Seq" ], 48 | "MinimumLevel": { 49 | "Default": "Verbose", 50 | "Override": { 51 | "System": "Information", 52 | "Microsoft": "Information", 53 | "Microsoft.EntityFrameworkCore": "Information" 54 | } 55 | }, 56 | "WriteTo": [ 57 | { 58 | "Name": "Seq", 59 | "Args": { 60 | "serverUrl": "http://localhost:5341", 61 | "apiKey": "none", 62 | "restrictedToMinimumLevel": "Verbose" 63 | } 64 | }, 65 | { 66 | "Name": "Async", 67 | "Args": { 68 | "configure": [ 69 | { 70 | "Name": "Console", 71 | "Args": { 72 | "restrictedToMinimumLevel": "Information" 73 | } 74 | } 75 | ] 76 | } 77 | } 78 | ], 79 | "Enrich": [ "FromLogContext", "WithExceptionDetails" ], 80 | "Properties": { 81 | "Environment": "LocalDev" 82 | } 83 | } 84 | ``` 85 | 86 | ## 3. Update Program.cs (minimal APIs) 87 | 88 | ``` cs 89 | // Logging based on https://github.com/jernejk/AspNetCoreSerilogExample and https://github.com/datalust/dotnet6-serilog-example 90 | // NOTE: When upgrading from .NET 5 or earlier, add `enable` to **.csproj** file under ``. 91 | // NOTE: While you can still use full Program.cs and Startup.cs, `.UseSerilog()` is marked as obsolete for them. It's safer to move to minimal APIs. 92 | using Serilog; 93 | using System.Diagnostics; 94 | 95 | try 96 | { 97 | var builder = WebApplication.CreateBuilder(args); 98 | 99 | builder.Host.UseSerilog((ctx, loggerConfiguration) => 100 | { 101 | loggerConfiguration 102 | .ReadFrom.Configuration(ctx.Configuration) 103 | .Enrich.FromLogContext() 104 | .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) 105 | .Enrich.WithProperty("Environment", ctx.HostingEnvironment); 106 | 107 | #if DEBUG 108 | // Used to filter out potentially bad data due debugging. 109 | // Very useful when doing Seq dashboards and want to remove logs under debugging session. 110 | loggerConfiguration.Enrich.WithProperty("DebuggerAttached", Debugger.IsAttached); 111 | #endif 112 | }); 113 | 114 | // Register services 115 | builder.Services.AddControllers(); 116 | builder.Services.AddLogging(); 117 | 118 | 119 | WebApplication app = builder.Build(); 120 | 121 | // Rest of configuration. 122 | if (app.Environment.IsDevelopment()) 123 | { 124 | app.UseDeveloperExceptionPage(); 125 | } 126 | 127 | // This will make the HTTP requests log as rich logs instead of plain text. 128 | app.UseSerilogRequestLogging(); 129 | 130 | app.UseRouting(); 131 | 132 | // Absolute minimum setup, just return "Hello world!" to browser. 133 | // You can use Controllers, SPA routing, SignalR, etc. routing. 134 | app.UseEndpoints(endpoints => 135 | { 136 | endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}"); 137 | endpoints.MapGet("", context => context.Response.WriteAsync("Hello World!\nUse /api/test/flatlog?input=Test, /api/test/StructuredLog?input=Test, etc. and observe console/Seq for logs.")); 138 | }); 139 | 140 | app.Run(); 141 | } 142 | catch (Exception ex) 143 | { 144 | if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger") 145 | { 146 | // Loading configuration or Serilog failed. 147 | // This will create a logger that can be captured by Azure logger. 148 | // To enable Azure logger, in Azure Portal: 149 | // 1. Go to WebApp 150 | // 2. App Service logs 151 | // 3. Enable "Application Logging (Filesystem)", "Application Logging (Filesystem)" and "Detailed error messages" 152 | // 4. Set Retention Period (Days) to 10 or similar value 153 | // 5. Save settings 154 | // 6. Under Overview, restart web app 155 | // 7. Go to Log Stream and observe the logs 156 | Log.Logger = new LoggerConfiguration() 157 | .MinimumLevel.Debug() 158 | .WriteTo.Console() 159 | .CreateLogger(); 160 | } 161 | 162 | Log.Fatal(ex, "Host terminated unexpectedly"); 163 | } 164 | finally 165 | { 166 | Log.Information("Shut down complete"); 167 | Log.CloseAndFlush(); 168 | } 169 | ``` 170 | --------------------------------------------------------------------------------