Skip to content

Commit 0e5402b

Browse files
committed
Improved the Readme
✅ Advanced Configuration section with authentication/secure connections (including Azure Cosmos DB) ✅ TTL/Auto-Expiration example for automatic log cleanup ✅ Exclude Redundant Fields example to reduce storage costs ✅ Rolling Collections guide with naming patterns and querying examples ✅ Migration Guide explaining legacy vs MongoDBBson differences ✅ Troubleshooting section covering common issues from GitHub ✅ Platform support updated to reflect .NET 6.0+
1 parent edb5916 commit 0e5402b

1 file changed

Lines changed: 140 additions & 5 deletions

File tree

README.md

Lines changed: 140 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
A Serilog sink that writes events as documents to [MongoDB](http://mongodb.org).
88

99
**Package** - [Serilog.Sinks.MongoDB](http://nuget.org/packages/serilog.sinks.mongodb)
10-
**Platforms** - .NET 4.7.2, .NET 6.0, .NET Standard 2.1
10+
**Platforms** - .NET 4.7.2, .NET 6.0+, .NET Standard 2.1
1111

1212
## Whats New
1313

@@ -106,21 +106,156 @@ Keys and values are not case-sensitive. This is an example of configuring the Mo
106106
}
107107
},
108108
"WriteTo": [
109-
{
110-
"Name": "MongoDBBson",
111-
"Args": {
109+
{
110+
"Name": "MongoDBBson",
111+
"Args": {
112112
"databaseUrl": "mongodb://username:password@ip:port/dbName?authSource=admin",
113113
"collectionName": "logs",
114114
"cappedMaxSizeMb": "1024",
115115
"cappedMaxDocuments": "50000",
116116
"rollingInterval": "Month"
117117
}
118-
}
118+
}
119119
]
120120
}
121121
}
122122
```
123123

124+
## Advanced Configuration
125+
126+
### Authentication & Secure Connections
127+
128+
For password-protected MongoDB instances, Azure Cosmos DB, or SSL/TLS connections:
129+
130+
```csharp
131+
var log = new LoggerConfiguration()
132+
.WriteTo.MongoDBBson(cfg =>
133+
{
134+
var mongoDbSettings = new MongoClientSettings
135+
{
136+
UseTls = true,
137+
AllowInsecureTls = false, // set true only for dev/testing
138+
Credential = MongoCredential.CreateCredential("databaseName", "username", "password"),
139+
Server = new MongoServerAddress("your-server.com", 27017)
140+
};
141+
142+
var mongoDbInstance = new MongoClient(mongoDbSettings).GetDatabase("logs");
143+
cfg.SetMongoDatabase(mongoDbInstance);
144+
})
145+
.CreateLogger();
146+
```
147+
148+
**Azure Cosmos DB** (MongoDB API):
149+
```csharp
150+
var connectionString = "mongodb://cosmosdb-account:key@cosmosdb-account.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false";
151+
var log = new LoggerConfiguration()
152+
.WriteTo.MongoDBBson(connectionString)
153+
.CreateLogger();
154+
```
155+
156+
### TTL / Auto-Expiration
157+
158+
Automatically delete old logs using MongoDB's TTL feature:
159+
160+
```csharp
161+
var log = new LoggerConfiguration()
162+
.WriteTo.MongoDBBson(cfg =>
163+
{
164+
cfg.SetMongoUrl("mongodb://localhost/logs");
165+
cfg.SetExpireTTL(TimeSpan.FromDays(30)); // logs expire after 30 days
166+
})
167+
.CreateLogger();
168+
```
169+
170+
### Exclude Redundant Fields
171+
172+
Reduce storage costs by excluding the `MessageTemplate` field (the rendered message is still stored):
173+
174+
```csharp
175+
var log = new LoggerConfiguration()
176+
.WriteTo.MongoDBBson(cfg =>
177+
{
178+
cfg.SetMongoUrl("mongodb://localhost/logs");
179+
cfg.SetExcludeMessageTemplate(true); // saves storage space
180+
})
181+
.CreateLogger();
182+
```
183+
184+
### Rolling Collections
185+
186+
Create time-based collections (e.g., one per day/month):
187+
188+
```csharp
189+
var log = new LoggerConfiguration()
190+
.WriteTo.MongoDBBson(cfg =>
191+
{
192+
cfg.SetMongoUrl("mongodb://localhost/logs");
193+
cfg.SetCollectionName("log");
194+
cfg.SetRollingInterval(RollingInterval.Day); // creates: log-20251004, log-20251005, etc.
195+
})
196+
.CreateLogger();
197+
```
198+
199+
**Collection naming patterns:**
200+
- `RollingInterval.Day``log-yyyyMMdd` (e.g., `log-20251004`)
201+
- `RollingInterval.Month``log-yyyyMM` (e.g., `log-202510`)
202+
- `RollingInterval.Year``log-yyyy` (e.g., `log-2025`)
203+
204+
**Querying rolling collections:**
205+
```csharp
206+
// Query specific date range - you need to target the correct collection(s)
207+
var collectionName = $"log-{DateTime.UtcNow:yyyyMMdd}";
208+
var collection = database.GetCollection<BsonDocument>(collectionName);
209+
var todayLogs = collection.Find(Builders<BsonDocument>.Filter.Empty).ToList();
210+
```
211+
212+
## Migration Guide
213+
214+
### From Legacy `.MongoDB()` to `.MongoDBBson()`
215+
216+
The legacy `.MongoDB()` sink converts logs to JSON then to BSON. The newer `.MongoDBBson()` writes structured BSON directly for better performance and features.
217+
218+
**Legacy (still supported):**
219+
```csharp
220+
.WriteTo.MongoDB("mongodb://localhost/logs") // converts to JSON first
221+
```
222+
223+
**New Bson sink (recommended):**
224+
```csharp
225+
.WriteTo.MongoDBBson("mongodb://localhost/logs") // native BSON
226+
```
227+
228+
**MongoDBBson exclusive features:**
229+
- TTL/Expiration (`SetExpireTTL`)
230+
- Exclude message template (`SetExcludeMessageTemplate`)
231+
- Rolling collections (`SetRollingInterval`)
232+
- Better type mapping and performance
233+
234+
## Troubleshooting
235+
236+
### MongoDB Connection Issues
237+
**Problem:** Application hangs or fails when MongoDB is unavailable
238+
**Solution:** Ensure your MongoDB connection string includes appropriate timeouts:
239+
```csharp
240+
"mongodb://localhost/logs?connectTimeoutMS=3000&serverSelectionTimeoutMS=3000"
241+
```
242+
243+
### Type Mapping Errors
244+
**Problem:** `System.Guid cannot be mapped to BsonValue`
245+
**Solution:** Ensure you're using the latest version (v7.1+) which includes Guid mapping fixes.
246+
247+
### Capped Collections Not Created
248+
**Problem:** Capped collection configuration not working
249+
**Solution:** Ensure the collection doesn't already exist. Drop existing collection first:
250+
```csharp
251+
database.DropCollection("logs");
252+
// Then configure with capped settings
253+
```
254+
255+
### Rolling Collections Not Named Correctly
256+
**Problem:** Collection created without time format suffix
257+
**Solution:** Ensure you're using `MongoDBBson` sink (not legacy `MongoDB`) and v7.1+.
258+
124259
## Icon
125260

126261
[MongoDB](https://icons8.com/icon/74402/mongodb) icon by [Icons8](https://icons8.com)

0 commit comments

Comments
 (0)