VanDerHeijden.Logging / src / VanDerHeijden.Logging.MongoDb / MongoDbLoggingExtensions.cs
Code · 27 lines · 870 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;


namespace VanDerHeijden.Logging.MongoDb;

public static class MongoDbLoggingExtensions
{
	public static IServiceCollection AddMongoDbLogging(this IServiceCollection services, IConfiguration configuration)
	{
		services.AddHttpContextAccessor();

		services.AddSingleton<IMongoCollection<LogEntry>>(sp =>
		{
			IMongoDatabase database = sp.GetRequiredService<IMongoDatabase>();
			string collectioname = configuration["MongoDb:Collections:Logs"] ?? "Logs";
			return database.GetCollection<LogEntry>(collectioname);
		});

		return services;
	}

	public static ILoggingBuilder AddMongoDbLogger(this ILoggingBuilder logging) =>
		logging.AddMongoDbLogger(sp => sp.GetRequiredService<IMongoCollection<LogEntry>>());
}