{"id":36967398,"url":"https://github.com/loresoft/serilog-sinks-mongo","last_synced_at":"2026-01-13T20:03:29.025Z","repository":{"id":326483048,"uuid":"1105037698","full_name":"loresoft/serilog-sinks-mongo","owner":"loresoft","description":"A high-performance Serilog sink that writes log events to MongoDB","archived":false,"fork":false,"pushed_at":"2026-01-12T09:14:45.000Z","size":108,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-01-12T18:39:28.249Z","etag":null,"topics":["mongodb","serilog","serilog-sink"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/loresoft.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"loresoft"}},"created_at":"2025-11-27T03:42:59.000Z","updated_at":"2026-01-12T09:14:41.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/loresoft/serilog-sinks-mongo","commit_stats":null,"previous_names":["loresoft/serilog-sinks-mongo"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/loresoft/serilog-sinks-mongo","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loresoft%2Fserilog-sinks-mongo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loresoft%2Fserilog-sinks-mongo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loresoft%2Fserilog-sinks-mongo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loresoft%2Fserilog-sinks-mongo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loresoft","download_url":"https://codeload.github.com/loresoft/serilog-sinks-mongo/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loresoft%2Fserilog-sinks-mongo/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28399508,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T14:36:09.778Z","status":"ssl_error","status_checked_at":"2026-01-13T14:35:19.697Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["mongodb","serilog","serilog-sink"],"created_at":"2026-01-13T20:03:28.416Z","updated_at":"2026-01-13T20:03:29.018Z","avatar_url":"https://github.com/loresoft.png","language":"C#","funding_links":["https://github.com/sponsors/loresoft"],"categories":[],"sub_categories":[],"readme":"# Serilog.Sinks.Mongo\n\n[![NuGet](https://img.shields.io/nuget/v/Serilog.Sinks.Mongo.svg)](https://www.nuget.org/packages/Serilog.Sinks.Mongo/)\n[![License](https://img.shields.io/github/license/loresoft/serilog-sinks-mongo.svg)](https://github.com/loresoft/serilog-sinks-mongo/blob/main/LICENSE)\n\nA high-performance [Serilog](https://serilog.net/) sink that writes log events to [MongoDB](https://www.mongodb.com/). This sink provides efficient batching, flexible configuration, and support for MongoDB-specific features like TTL indexes and capped collections.\n\n## Features\n\n- **Batched Writes** - Efficient batch processing of log events\n- **Automatic Expiration** - TTL index support for automatic log rotation\n- **Capped Collections** - Size and document count limited collections\n- **Flexible Configuration** - Code-based and configuration file support\n- **Customizable Document Format** - Extensible document factory pattern\n- **High Performance** - Asynchronous writes with configurable buffering\n\n## Installation\n\nInstall via NuGet:\n\n```bash\ndotnet add package Serilog.Sinks.Mongo\n```\n\nOr using Package Manager Console:\n\n```powershell\nInstall-Package Serilog.Sinks.Mongo\n```\n\n## Quick Start\n\n### Basic Usage\n\n```csharp\nusing Serilog;\n\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"logs\"\n    )\n    .CreateLogger();\n\nLog.Information(\"Hello, MongoDB!\");\nLog.CloseAndFlush();\n```\n\n### With TTL Index (Automatic Expiration)\n\n```csharp\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"logs\",\n        expireAfter: TimeSpan.FromDays(30) // Logs expire after 30 days\n    )\n    .CreateLogger();\n```\n\n### With Capped Collection\n\n```csharp\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"logs\",\n        maxDocuments: 10000, // Maximum 10,000 documents\n        maxSize: 10485760    // Maximum 10 MB\n    )\n    .CreateLogger();\n```\n\n## Configuration\n\n### Code-Based Configuration\n\n#### Using Connection String\n\n```csharp\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"logs\",\n        minimumLevel: LogEventLevel.Information,\n        expireAfter: TimeSpan.FromDays(7),\n        batchSizeLimit: 100,\n        bufferingTimeLimit: TimeSpan.FromSeconds(2)\n    )\n    .CreateLogger();\n```\n\n#### Using MongoUrl\n\n```csharp\nvar mongoUrl = new MongoUrl(\"mongodb://localhost:27017\");\n\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        mongoUrl: mongoUrl,\n        databaseName: \"serilog\",\n        collectionName: \"logs\"\n    )\n    .CreateLogger();\n```\n\n#### Using Options Configuration\n\n```csharp\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(options =\u003e\n    {\n        options.ConnectionString = \"mongodb://localhost:27017\";\n        options.DatabaseName = \"serilog\";\n        options.CollectionName = \"logs\";\n        options.MinimumLevel = LogEventLevel.Debug;\n        options.ExpireAfter = TimeSpan.FromDays(30);\n        options.BatchSizeLimit = 100;\n        options.BufferingTimeLimit = TimeSpan.FromSeconds(5);\n        \n        // Capped collection options\n        options.CollectionOptions = new CreateCollectionOptions\n        {\n            Capped = true,\n            MaxSize = 5242880,    // 5 MB\n            MaxDocuments = 1000\n        };\n        \n        // Custom properties to promote to top-level\n        options.Properties = new HashSet\u003cstring\u003e \n        { \n            \"SourceContext\", \n            \"RequestId\",\n            \"UserId\"\n        };\n        \n        // Remove promoted properties from nested Properties object\n        options.OptimizeProperties = true;\n    })\n    .CreateLogger();\n```\n\n### JSON Configuration (appsettings.json)\n\n```json\n{\n  \"Serilog\": {\n    \"Using\": [\"Serilog.Sinks.Mongo\", \"Serilog.Sinks.Console\"],\n    \"MinimumLevel\": {\n      \"Default\": \"Information\",\n      \"Override\": {\n        \"Microsoft\": \"Warning\",\n        \"System\": \"Warning\"\n      }\n    },\n    \"WriteTo\": [\n      {\n        \"Name\": \"MongoDB\",\n        \"Args\": {\n          \"connectionString\": \"mongodb://localhost:27017\",\n          \"databaseName\": \"serilog\",\n          \"collectionName\": \"logs\",\n          \"expireAfter\": \"30.00:00:00\"\n        }\n      }\n    ],\n    \"Enrich\": [\"FromLogContext\"]\n  }\n}\n```\n\nThen in your code:\n\n```csharp\nusing Serilog;\nusing Microsoft.Extensions.Configuration;\n\nvar configuration = new ConfigurationBuilder()\n    .AddJsonFile(\"appsettings.json\")\n    .Build();\n\nLog.Logger = new LoggerConfiguration()\n    .ReadFrom.Configuration(configuration)\n    .CreateLogger();\n```\n\n## Configuration Options\n\n### MongoSinkOptions\n\n| Property             | Default             | Description                                                                      |\n| -------------------- | ------------------- | -------------------------------------------------------------------------------- |\n| `ConnectionString`   | `null`              | MongoDB connection string                                                        |\n| `MongoUrl`           | `null`              | Alternative to ConnectionString (takes precedence if both are set)               |\n| `DatabaseName`       | `\"serilog\"`         | Database name                                                                    |\n| `CollectionName`     | `\"logs\"`            | Collection name                                                                  |\n| `MinimumLevel`       | `Verbose`           | Minimum log event level to write                                                 |\n| `LevelSwitch`        | `null`              | Dynamically controls the minimum log level at runtime                            |\n| `ExpireAfter`        | `null`              | Time-to-live for automatic document expiration (creates TTL index on Timestamp)  |\n| `BatchSizeLimit`     | `100`               | Maximum number of events to include in a single batch                            |\n| `BufferingTimeLimit` | `00:00:02`          | Maximum time to wait before writing a batch                                      |\n| `CollectionOptions`  | `null`              | MongoDB collection creation options (capped collections, time-series, etc.)      |\n| `Properties`         | `{\"SourceContext\"}` | Property names to promote from Properties object to document top-level           |\n| `OptimizeProperties` | `false`             | Remove promoted properties from nested Properties object to avoid duplication    |\n| `DocumentFactory`    | `null`              | Custom document factory for converting log events to BSON                        |\n| `MongoFactory`       | `null`              | Custom MongoDB factory for client/database/collection management                 |\n\n## Document Structure\n\nBy default, log events are stored with the following structure:\n\n```json\n{\n  \"_id\": ObjectId(\"...\"),\n  \"Timestamp\": ISODate(\"2025-11-27T10:30:00.000Z\"),\n  \"Level\": \"Information\",\n  \"Message\": \"User logged in successfully\",\n  \"TraceId\": \"00-abc123...\",\n  \"SpanId\": \"def456...\",\n  \"SourceContext\": \"MyApp.Controllers.AuthController\",\n  \"Properties\": {\n    \"UserId\": \"12345\",\n    \"Username\": \"john.doe\",\n    \"IPAddress\": \"192.168.1.1\"\n  },\n  \"Exception\": {\n    \"Message\": \"...\",\n    \"Type\": \"System.Exception\",\n    \"Text\": \"...\",\n    \"HResult\": -2146233088\n  }\n}\n```\n\n### Property Promotion\n\nProperties can be promoted from the `Properties` object to the top level of the document:\n\n```csharp\noptions.Properties = new HashSet\u003cstring\u003e \n{ \n    \"SourceContext\",\n    \"RequestId\",\n    \"UserId\",\n    \"MachineName\"\n};\n```\n\nThis results in:\n\n```json\n{\n  \"_id\": ObjectId(\"...\"),\n  \"Timestamp\": ISODate(\"2025-11-27T10:30:00.000Z\"),\n  \"Level\": \"Information\",\n  \"Message\": \"Processing request\",\n  \"SourceContext\": \"MyApp.Services.ProcessingService\",\n  \"RequestId\": \"req-789\",\n  \"UserId\": \"12345\",\n  \"MachineName\": \"WEB-SERVER-01\",\n  \"Properties\": {\n    // Other properties...\n  }\n}\n```\n\n#### Optimizing Property Storage\n\nBy default, promoted properties appear both at the top level and within the nested `Properties` object. To reduce document size and avoid duplication, enable `OptimizeProperties`:\n\n```csharp\noptions.Properties = new HashSet\u003cstring\u003e { \"SourceContext\", \"RequestId\", \"UserId\" };\noptions.OptimizeProperties = true; // Removes promoted properties from nested Properties\n```\n\nWith `OptimizeProperties` enabled, promoted properties are removed from the `Properties` object after being promoted to the top level.\n\n## Custom Document Factory\n\nImplement `IDocumentFactory` to customize the document structure:\n\n```csharp\npublic class CustomDocumentFactory : DocumentFactory\n{\n    public override BsonDocument? CreateDocument(LogEvent logEvent, MongoSinkOptions options)\n    {\n        var document = base.CreateDocument(logEvent, options);\n        \n        if (document != null)\n        {\n            // Add custom fields\n            document[\"Application\"] = \"MyApp\";\n            document[\"Environment\"] = \"Production\";\n            \n            // Custom transformations\n            if (logEvent.Properties.TryGetValue(\"RequestPath\", out var path))\n            {\n                document[\"Path\"] = path.ToString();\n            }\n        }\n        \n        return document;\n    }\n}\n\n// Use the custom factory\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(options =\u003e\n    {\n        options.ConnectionString = \"mongodb://localhost:27017\";\n        options.DatabaseName = \"serilog\";\n        options.CollectionName = \"logs\";\n        options.DocumentFactory = new CustomDocumentFactory();\n    })\n    .CreateLogger();\n```\n\n## Advanced Scenarios\n\n### Multiple Sinks with Different Configurations\n\n```csharp\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"errors\",\n        minimumLevel: LogEventLevel.Error\n    )\n    .WriteTo.MongoDB(\n        connectionString: \"mongodb://localhost:27017\",\n        databaseName: \"serilog\",\n        collectionName: \"all-logs\",\n        minimumLevel: LogEventLevel.Information,\n        expireAfter: TimeSpan.FromDays(7)\n    )\n    .CreateLogger();\n```\n\n### With Microsoft.Extensions.Hosting\n\n```csharp\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddSerilog(loggerConfiguration =\u003e\n{\n    loggerConfiguration\n        .MinimumLevel.Information()\n        .Enrich.FromLogContext()\n        .WriteTo.Console()\n        .WriteTo.MongoDB(\n            connectionString: \"mongodb://localhost:27017\",\n            databaseName: \"serilog\",\n            collectionName: \"logs\",\n            expireAfter: TimeSpan.FromDays(30)\n        );\n});\n\nvar host = builder.Build();\nawait host.RunAsync();\n```\n\n## Performance Tuning\n\n### Batch Configuration\n\nAdjust batching settings based on your throughput requirements:\n\n```csharp\noptions.BatchSizeLimit = 500;           // Larger batches for high throughput\noptions.BufferingTimeLimit = TimeSpan.FromSeconds(10); // Longer wait for batch fill\n```\n\n## MongoDB Collection Strategies\n\n### TTL Index (Time-Based Expiration)\n\nBest for applications that need automatic log cleanup:\n\n```csharp\n.WriteTo.MongoDB(\n    connectionString: \"mongodb://localhost:27017\",\n    databaseName: \"serilog\",\n    collectionName: \"logs\",\n    expireAfter: TimeSpan.FromDays(30)\n)\n```\n\nA TTL index is automatically created on the `Timestamp` field to removes expired documents.\n\n### Capped Collection (Size/Count Limited)\n\nBest for fixed-size log storage:\n\n```csharp\n.WriteTo.MongoDB(\n    connectionString: \"mongodb://localhost:27017\",\n    databaseName: \"serilog\",\n    collectionName: \"logs\",\n    maxDocuments: 100000,  // Keep latest 100k documents\n    maxSize: 104857600     // Or 100 MB, whichever is hit first\n)\n```\n\nOldest documents are automatically removed when limits are reached.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floresoft%2Fserilog-sinks-mongo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floresoft%2Fserilog-sinks-mongo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floresoft%2Fserilog-sinks-mongo/lists"}