{"id":23109307,"url":"https://github.com/sangeethnandakumar/template-serilog","last_synced_at":"2026-03-20T00:37:50.715Z","repository":{"id":45804908,"uuid":"283860096","full_name":"sangeethnandakumar/Template-Serilog","owner":"sangeethnandakumar","description":"This repository holds an example template structure for creating a logger in .NET Core applications with Serilog with proper implementations","archived":false,"fork":false,"pushed_at":"2024-02-05T06:15:39.000Z","size":2354,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-03T23:15:38.996Z","etag":null,"topics":["debug","error","logger","logging","serilog","verbose"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sangeethnandakumar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2020-07-30T19:26:40.000Z","updated_at":"2023-09-11T10:49:14.000Z","dependencies_parsed_at":"2023-09-11T11:19:59.079Z","dependency_job_id":null,"html_url":"https://github.com/sangeethnandakumar/Template-Serilog","commit_stats":null,"previous_names":["sangeethnandakumar/serilog-template"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sangeethnandakumar/Template-Serilog","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sangeethnandakumar%2FTemplate-Serilog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sangeethnandakumar%2FTemplate-Serilog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sangeethnandakumar%2FTemplate-Serilog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sangeethnandakumar%2FTemplate-Serilog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sangeethnandakumar","download_url":"https://codeload.github.com/sangeethnandakumar/Template-Serilog/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sangeethnandakumar%2FTemplate-Serilog/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28559347,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T00:46:33.223Z","status":"online","status_checked_at":"2026-01-19T02:00:08.049Z","response_time":67,"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":["debug","error","logger","logging","serilog","verbose"],"created_at":"2024-12-17T01:35:44.810Z","updated_at":"2026-01-19T03:01:32.214Z","avatar_url":"https://github.com/sangeethnandakumar.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Structured Logging - Simplified\nThis is a Serilog installation template that can work in tandem with Microsoft's `ILogger` interface and provides structured logging support\n\n![alt text](https://code.4noobz.net/wp-content/uploads/2021/10/serilog-logo.png)\n\n# IMPLEMENTING IN - WebAPIs\n## Install Packages\n```xml\n    \u003c!-- LOGGING PROVIDERS--\u003e\n    \u003cPackageReference Include=\"Serilog\" Version=\"3.1.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Extensions.Hosting\" Version=\"8.0.0\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Settings.Configuration\" Version=\"8.0.0\" /\u003e\n\n    \u003c!-- LOGGING SINKS--\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.Console\" Version=\"5.0.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.File\" Version=\"5.0.0\" /\u003e\n```\n\n## Create An Extension Method `UseSerilogConfiguration()`\n```csharp\nusing Serilog;\nnamespace Instaread.BestSellingScrapper.API.Extensions\n{\n    public static class SerilogExtensions\n    {\n        public static IHostBuilder UseSerilogConfiguration(this IHostBuilder builder)\n        {\n            builder.UseSerilog((context, services, configuration) =\u003e\n            {\n                configuration.ReadFrom.Configuration(context.Configuration);\n            });\n            return builder;\n        }\n    }\n}\n```\n\n## Call Extension Method From `Program.cs`\n```csharp\nusing Instaread.BestSellingScrapper.API.Extensions;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Configure Serilog\nbuilder.Host.UseSerilogConfiguration();\n\nbuilder.Services.AddControllers();\nbuilder.Services.AddEndpointsApiExplorer();\nbuilder.Services.AddSwaggerGen();\n```\n\n## Lastly Put This In `appsettings.json`\n```json\n{\n  \"Serilog\": {\n    \"Using\": [ \"Serilog.Sinks.Console\", \"Serilog.Sinks.File\" ],\n    \"MinimumLevel\": {\n      \"Default\": \"Information\",\n      \"Override\": {\n        \"Microsoft.AspNetCore.Hosting\": \"Warning\",\n        \"Microsoft.AspNetCore.Mvc\": \"Warning\",\n        \"Microsoft.AspNetCore.Routing.EndpointMiddleware\": \"Warning\",\n        \"Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker\": \"Warning\"\n      }\n    },\n    \"WriteTo\": [\n      {\n        \"Name\": \"Console\",\n        \"Args\": {\n          \"outputTemplate\": \"{Timestamp:dd/MM/yy hh:mm:ss tt} [{Level:u3}] {Message}{NewLine}{Exception}\"\n        }\n      },\n      {\n        \"Name\": \"File\",\n        \"Args\": {\n          \"path\": \"Logs/log.txt\",\n          \"rollingInterval\": \"Day\",\n          \"retainedFileCountLimit\": 5,\n          \"fileSizeLimitBytes\": 20000000,\n          \"rollOnFileSizeLimit\": true,\n          \"outputTemplate\": \"{Timestamp:dd/MM/yy hh:mm:ss tt} [{Level:u3}] {Message}{NewLine}{Exception}\"\n        }\n      }\n    ],\n    \"Properties\": {\n      \"Application\": \"Instaread.BestSellingScrapper.API\"\n    }\n  }\n}\n```\n\n## Now Just Inject And Use `ILogger`\n```csharp\n[HttpGet(Name = \"GetWeatherForecast\")]\npublic IEnumerable\u003cWeatherForecast\u003e Get()\n{\n    //Simple logging\n    _logger.LogDebug(\"This is a debug log\");\n\n    //Structured Logging\n    _logger.LogInfo(\"It is very expensive at {Cost} rupees per piece\", 120 );\n\n    //Structured Logging With JSON serializing\n    _logger.LogWarning(\"This data will get serialized on logs {@Data}\", new { Name=\"Sangeeth\" });\n\n    return data;\n}\n```\n\n# IMPLEMENTING IN - CONSOLE App\nYour project need to install the following Serilog nuget modules to configure logging. Install the following packages from nuget\n\n## Step 1: Install Required NuGet Libraries\nInstall the following NuGet packages\n```xml\n  \u003cItemGroup\u003e\n    \u003cPackageReference Include=\"Ben.Demystifier\" Version=\"0.4.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog\" Version=\"2.11.0\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.Async\" Version=\"1.5.0\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.Console\" Version=\"4.0.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.File\" Version=\"5.0.0\" /\u003e\n  \u003c/ItemGroup\u003e\n```\n\n## Step 2: Copy class 'Setup.cs'\nCopy the Setup.cs file to your app\n```csharp\nusing Serilog;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ConsoleApp\n{\n    public static class Setup\n    {\n        /// \u003csummary\u003e\n        /// Sets the logger up and running\n        /// \u003c/summary\u003e\n        public static void Serilog()\n        {\n            const string OUTPUT_TEMPLATE = \"{Timestamp:MM/dd/yyyy hh:mm:ss tt} [{Level}] {Message}{NewLine}{Exception}\";\n            Log.Logger = new LoggerConfiguration()\n            .MinimumLevel.Debug()\n            .WriteTo.Console(\n                outputTemplate: OUTPUT_TEMPLATE\n                )\n            .WriteTo.Async(x =\u003e\n                x.File(@\"D:\\Logs\\log.txt\",\n                outputTemplate: OUTPUT_TEMPLATE,\n                rollingInterval: RollingInterval.Day, //Creates new file daily\n                retainedFileCountLimit: 5, //Maintains 5 log files at a time. Auto delete older logs\n                fileSizeLimitBytes: 20 * 1000000, //If log grows \u003e 20MB, Splits into new log file\n                rollOnFileSizeLimit: true)\n            )\n            .CreateLogger();\n        }\n\n        /// \u003csummary\u003e\n        /// Enrich exceptions with hints for better troubleshooting\n        /// \u003c/summary\u003e\n        /// \u003cparam name=\"message\"\u003e\u003c/param\u003e\n        /// \u003cparam name=\"hints\"\u003e\u003c/param\u003e\n        /// \u003cparam name=\"ex\"\u003e\u003c/param\u003e\n        /// \u003creturns\u003e\u003c/returns\u003e\n        public static string AddHints(this string message, object hints, Exception ex = null)\n        {\n            var sw = new Stopwatch();\n            sw.Start();\n            var renderHints = JsonSerializer.Serialize(hints, new JsonSerializerOptions { WriteIndented = true });\n            var builder = new StringBuilder(message);\n            builder.Append(\"\\nHints:\");\n            builder.Append(renderHints.Substring(1, renderHints.Length - 2));\n            if (ex != null)\n            {\n                builder.Append(\"\\nException:\\n\");\n                builder.Append(ex.Demystify().StackTrace);\n            }\n            builder.Append(\"\\n------------------------------------------------------------------\\n\");\n            sw.Stop();\n            Console.WriteLine(sw.ElapsedMilliseconds);\n            return builder.ToString();\n        }\n    }\n}\n```\n\n## Step 3: Setup Serilog\nCall Configure Serilog before anything\n```csharp\n    //Setup Logger\n    Configure.Serilog();\n```\n\n## Step 4: Implement Logger\nImplement the logger as follows\n```csharp\n\tusing Serilog;\n\t\n\t//Setup Logger\n\tConfigure.Serilog();\n\t\n\t//Write some usefull logs\n\tLog.Information(\"Info error\");\n\tLog.Warning(\"Warning error\");\n\t\n\t//Write some exception logs\n\ttry\n\t{\n\t\tLog.Information(\"Info error\");\n\t\tthrow new StackOverflowException();\n\t}\n\tcatch (Exception ex)\n\t{\n\t\t//Catch exceptions and write hints\n\t\tLog.Error(\"An exception occured.\".AddHints(\n\t\t\tnew\n\t\t\t{\n\t\t\t\tA = \"Value of A\",\n\t\t\t\tB = \"Value of B\",\n\t\t\t\tC = new { Fname = \"Sangee\", LName = \"Nandakumar\" }\n\t\t\t}\n\t\t, ex));\n\t}\n\tConsole.Read();\n```\n\n# IMPLEMENTING IN - ASP.NET WebApp\nYour project need to install the following Serilog nuget modules to configure logging. Install the following packages from nuget\n\n## Step 1: Install Required NuGet Libraries\nInstall the following NuGet packages\n```xml\n\u003cItemGroup\u003e\n    \u003cPackageReference Include=\"Ben.Demystifier\" Version=\"0.4.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog\" Version=\"3.0.1\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.Async\" Version=\"1.5.0\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.Console\" Version=\"4.1.0\" /\u003e\n    \u003cPackageReference Include=\"Serilog.Sinks.File\" Version=\"5.0.0\" /\u003e\n\u003c/ItemGroup\u003e\n```\n\n## Step 2: Copy class 'Configure.cs'\nCopy the Configure.cs file to your app\n\n### If using Seq, Add this sink also\n```csharp\n .WriteTo.Async(x =\u003e\n                x.Seq(\"https://seq.twileloop.com\", apiKey: \"*****\")\n            )\n```\n\n```csharp\nusing ConsoleApp;\nusing Serilog;\n\n//Setup Logger\nSetup.Serilog();\n\n//Write some usefull logs\nLog.Information(\"Info error\");\nLog.Warning(\"Warning error\");\n\n//Write some exception logs\ntry\n{\n    Log.Information(\"Info error\");\n    throw new StackOverflowException();\n}\ncatch (Exception ex)\n{\n    //Catch exceptions and write hints\n    Log.Error(\"An exception occured.\".AddHints(\n        new\n        {\n            A = \"Value of A\",\n            B = \"Value of B\",\n            C = new { Fname = \"Sangee\", LName = \"Nandakumar\" }\n        }\n        , ex));\n}\n\nConsole.Read();\n```\n\n## Step 3: Setup Serilog\nWrap everything ina try-catch and add\n```csharp\nConfigure.Serilog(builder);\n```\nafter var builder = WebApplication.CreateBuilder(args);`\n\n### General configuration\n\n```csharp\nusing Serilog;\nusing WebApp;\n\ntry\n{\n    var builder = WebApplication.CreateBuilder(args);\n    Configure.Serilog(builder);\n    builder.Services.AddControllers();\n    builder.Services.AddEndpointsApiExplorer();\n    builder.Services.AddSwaggerGen();\n    var app = builder.Build();\n\n    if (app.Environment.IsDevelopment())\n    {\n        app.UseSwagger();\n        app.UseSwaggerUI();\n    }\n    app.UseHttpsRedirection();\n    app.UseAuthorization();\n    app.MapControllers();\n    app.Run();\n    return 0;\n}\ncatch (Exception ex)\n{\n    Log.Fatal(ex, \"Host terminated unexpectedly\");\n    return 1;\n}\nfinally\n{\n    Log.CloseAndFlush();\n}\n```\n\n## Step 4: Write logs\n\n## Write structured logs\n```\nLog.Information(\"Processed {@SensorInput} in {TimeMS:000} ms\", new { Latitude = 25, Longitude = 134 }, 34);\n```\n\n## Write logs anywhere\n```csharp\n    [ApiController]\n    [Route(\"[controller]\")]\n    public class WeatherForecastController : ControllerBase\n    {\n        [HttpGet(Name = \"GetWeatherForecast\")]\n        public IActionResult Get()\n        {\n            Log.Debug(\"Some sample logs\");\n            Log.Information(\"Some sample logs\");\n            Log.Warning(\"Some sample logs\");\n            try\n            {\n                throw new Exception(\"This is a test exception\");\n            }\n            catch (Exception ex)\n            {\n                //Catch exceptions and write hints\n                Log.Error(\"An exception occured.\".AddHints(\n                    new\n                    {\n                        A = \"Value of A\",\n                        B = \"Value of B\",\n                        C = new { Fname = \"Sangee\", LName = \"Nandakumar\" }\n                    }\n                    , ex));\n            }\n            finally\n            {\n            }\n            return Ok(1);\n        }\n    }\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsangeethnandakumar%2Ftemplate-serilog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsangeethnandakumar%2Ftemplate-serilog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsangeethnandakumar%2Ftemplate-serilog/lists"}