{"id":23626349,"url":"https://github.com/datalust/dotnet6-serilog-example","last_synced_at":"2025-08-31T02:31:48.423Z","repository":{"id":41450656,"uuid":"426781064","full_name":"datalust/dotnet6-serilog-example","owner":"datalust","description":"A sample project showing Serilog configured in the default .NET 6 web application template","archived":false,"fork":false,"pushed_at":"2021-11-14T21:52:14.000Z","size":143,"stargazers_count":195,"open_issues_count":1,"forks_count":41,"subscribers_count":9,"default_branch":"dev","last_synced_at":"2025-04-01T10:35:39.427Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datalust.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-11-10T21:24:23.000Z","updated_at":"2025-02-11T13:07:42.000Z","dependencies_parsed_at":"2022-08-10T02:27:08.374Z","dependency_job_id":null,"html_url":"https://github.com/datalust/dotnet6-serilog-example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/datalust/dotnet6-serilog-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalust%2Fdotnet6-serilog-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalust%2Fdotnet6-serilog-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalust%2Fdotnet6-serilog-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalust%2Fdotnet6-serilog-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datalust","download_url":"https://codeload.github.com/datalust/dotnet6-serilog-example/tar.gz/refs/heads/dev","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datalust%2Fdotnet6-serilog-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":272931173,"owners_count":25017313,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-31T02:00:09.071Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-27T22:53:03.594Z","updated_at":"2025-08-31T02:31:48.127Z","avatar_url":"https://github.com/datalust.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# `net6.0` Serilog example\n\nThis is a sample project showing Serilog configured in the default .NET 6 web application template.\n\nTo show how everything fits together, the sample includes:\n\n * Support for .NET 6's `ILogger\u003cT\u003e` and `WebApplicationBuilder`\n * Namespace-specific logging levels to suppress noise from the framework\n * JSON configuration\n * Clean, themed console output\n * Local logging to a rolling file\n * Centralized structured logging with Seq\n * Streamlined HTTP request logging\n * Filtering out of noisy events using _Serilog.Expressions_\n * Exception logging\n * Fallback/fail-safe bootstrap logger\n * Proper flushing of logs at exit\n\nThe code is not commented, so that the structure is easier to compare with the default template. If you're keen \nto understand the trade-offs and reasoning behind the choices made here, there's some commentary on each section\nin _Setting up from scratch_ below.\n\n## Trying it out\n\nYou'll need the .NET 6.0 SDK or later to run the sample. Check the version you have installed with:\n\n```shell\ndotnet --version\n```\n\nAfter checking out this repository or downloading a zip file of the source code, you can run the project with:\n\n```shell\ndotnet run\n```\n\nSome URLs will be printed to the terminal: open them in a browser to see request logging in action.\n\n * `/` \u0026mdash; should show \"Hello, world!\" and respond successfully\n * `/oops` \u0026mdash; throws an exception, which will be logged\n\nTo see structured log output, start a temporary local Seq instance with:\n\n```shell\ndocker run --rm -it -e ACCEPT_EULA=y -p 5341:80 datalust/seq\n```\n\nand open `http://localhost:5341` in your browser (for Windows users, there's also an MSI at https://datalust.co/download).\n\n## Setting up from scratch\n\nYou can freely copy code from this project to your own applications. If you'd like to set up from scratch, and skip any steps that aren't relevant to you,\ntry following the steps below.\n\n### 1. Create the project using the `web` template\n\n```shell\nmkdir dotnet6-serilog-example\ncd dotnet6-serilog-example\ndotnet new web\n```\n\n### 2. Install Serilog packages\n\n```shell\ndotnet add package serilog.aspnetcore\ndotnet add package serilog.sinks.seq\ndotnet add package serilog.expressions\n```\n\n### 3. Initialize Serilog at the start of `Program.cs`\n\nIts important that logging is initialized as early as possible, so that errors that might prevent your app from starting are logged.\n\nAt the very top of `Program.cs`:\n\n```csharp\nusing Serilog;\n\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.Console()\n    .CreateBootstrapLogger();\n\nLog.Information(\"Starting up\");\n```\n\n`CreateBootstrapLogger()` sets up Serilog so that the initial logger configuration (which writes only to `Console`), can be swapped \nout later in the initialization process, once the web hosting infrastructure is available.\n\n### 4. Wrap the rest of `Program.cs` in `try`/`catch`/`finally`\n\nConfiguration of the web application in `Program.cs` can now be enclosed in a `try` block.\n\n```csharp\ntry\n{\n    // \u003csnip\u003e\n}\ncatch (Exception ex)\n{\n    Log.Fatal(ex, \"Unhandled exception\");\n}\nfinally\n{\n    Log.Information(\"Shut down complete\");\n    Log.CloseAndFlush();\n}\n```\n\nThe `catch` block will log any exceptions thrown during start-up.\n\nThe `Log.CloseAndFlush()` in the `finally` block ensures that any queued log events will be properly recorded when the program exits.\n\n### 5. Wire Serilog into the `WebApplicationBuilder`\n\n```csharp\n    builder.Host.UseSerilog((ctx, lc) =\u003e lc\n        .WriteTo.Console()\n        .ReadFrom.Configuration(ctx.Configuration));\n```\n\n### 6. Replace logging configuration in `appsettings.json`\n\nIn `appsettings.json`, remove `\"Logging\"` and add `\"Serilog\"`.\n\nThe complete JSON configuration from the example is:\n\n```json\n{\n  \"Serilog\": {\n    \"MinimumLevel\": {\n      \"Default\": \"Information\",\n      \"Override\": {\n        \"Microsoft\": \"Warning\",\n        \"Microsoft.Hosting.Lifetime\": \"Information\"\n      }\n    },\n    \"Filter\": [\n      {\n        \"Name\": \"ByExcluding\",\n        \"Args\": {\n          \"expression\": \"@mt = 'An unhandled exception has occurred while executing the request.'\"\n        }\n      }\n    ],\n    \"WriteTo\": [\n      {\n        \"Name\": \"File\",\n        \"Args\": { \"path\":  \"./logs/log-.txt\", \"rollingInterval\": \"Day\" }\n      },\n      {\n        \"Name\": \"Seq\",\n        \"Args\": { \"serverUrl\":  \"http://localhost:5341\" }\n      }\n    ]\n  },\n  \"AllowedHosts\": \"*\"\n}\n```\n\nRemove all `\"Logging\"` configuration from `appsettings.Development.json`. (During development, you should normally use the same logging\nlevel as you use in production; if you can't find problems using the production logs in development, you'll have an even harder time\nfinding problems in the real production environment.)\n\n### 7. Add Serilog's request logging middleware\n\nBy default, the ASP.NET Core framework logs multiple information-level events per request.\n\nSerilog's request logging streamlines this, into a single message per request, including path, method, timings, status code, and exception.\n\n```csharp\n    app.UseSerilogRequestLogging();\n```\n\n## Writing log events\n\nThis setup enables both Serilog's static `Log` class, as you see used in the example above, and _Microsoft.Extensions.Logging_'s\n`ILogger\u003cT\u003e`, which can be consumed through dependency injection into controllers and other components.\n\n## Viewing structured logs\n\nIf you're running a local Seq instance, you can now view the structured properties attached to your application logs in the Seq UI:\n\n![Application logs in Seq](https://github.com/datalust/dotnet6-serilog-example/blob/dev/asset/structured-data-in-seq.png)\n\n## Getting help and advice\n\nAsk your question on [Stack Overflow](https://stackoverflow.com) and tag it with `serilog`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatalust%2Fdotnet6-serilog-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatalust%2Fdotnet6-serilog-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatalust%2Fdotnet6-serilog-example/lists"}