|
| 1 | + |
| 2 | +using Serilog; |
| 3 | +using Serilog.Configuration; |
| 4 | +using Serilog.Events; |
| 5 | +using Serilog.Sinks.PeriodicBatching; |
| 6 | +using SharpCoreDB.Interfaces; |
| 7 | +using SharpCoreDB.Services; |
| 8 | +using Microsoft.Extensions.DependencyInjection; |
| 9 | +namespace SharpCoreDB.Serilog.Sinks; |
| 10 | +/// Michel Posseth |
| 11 | +/// <summary> |
| 12 | +/// Extension methods for configuring the SharpCoreDB sink with Serilog. |
| 13 | +/// </summary> |
| 14 | +public static class LoggerConfigurationExtensions |
| 15 | +{ |
| 16 | + private const int DefaultBatchPostingLimit = 50; |
| 17 | + private static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2); |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// Writes log events to a SharpCoreDB database using the provided database instance. |
| 21 | + /// </summary> |
| 22 | + /// <param name="loggerSinkConfiguration">The logger sink configuration.</param> |
| 23 | + /// <param name="database">The SharpCoreDB database instance to write to.</param> |
| 24 | + /// <param name="tableName">The name of the table to write logs to (default: "Logs").</param> |
| 25 | + /// <param name="restrictedToMinimumLevel">The minimum log level (default: Verbose).</param> |
| 26 | + /// <param name="batchPostingLimit">The maximum number of events to include in a single batch (default: 50).</param> |
| 27 | + /// <param name="period">The time to wait between checking for event batches (default: 2 seconds).</param> |
| 28 | + /// <param name="autoCreateTable">Whether to automatically create the table if it doesn't exist (default: true).</param> |
| 29 | + /// <param name="storageEngine">The storage engine to use (default: "AppendOnly").</param> |
| 30 | + /// <returns>Logger configuration, allowing chaining.</returns> |
| 31 | + public static LoggerConfiguration SharpCoreDB( |
| 32 | + this LoggerSinkConfiguration loggerSinkConfiguration, |
| 33 | + IDatabase database, |
| 34 | + string tableName = "Logs", |
| 35 | + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, |
| 36 | + int batchPostingLimit = DefaultBatchPostingLimit, |
| 37 | + TimeSpan? period = null, |
| 38 | + bool autoCreateTable = true, |
| 39 | + string storageEngine = "AppendOnly") |
| 40 | + { |
| 41 | + ArgumentNullException.ThrowIfNull(loggerSinkConfiguration); |
| 42 | + |
| 43 | + ArgumentNullException.ThrowIfNull(database); |
| 44 | + |
| 45 | + var actualPeriod = period ?? DefaultPeriod; |
| 46 | + |
| 47 | + var sink = new SharpCoreDBSink( |
| 48 | + database, |
| 49 | + tableName, |
| 50 | + autoCreateTable, |
| 51 | + storageEngine); |
| 52 | + |
| 53 | + var batchingOptions = new PeriodicBatchingSinkOptions |
| 54 | + { |
| 55 | + BatchSizeLimit = batchPostingLimit, |
| 56 | + Period = actualPeriod, |
| 57 | + EagerlyEmitFirstEvent = true, |
| 58 | + QueueLimit = 10000 |
| 59 | + }; |
| 60 | + |
| 61 | + var batchingSink = new PeriodicBatchingSink(sink, batchingOptions); |
| 62 | + |
| 63 | + return loggerSinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel); |
| 64 | + } |
| 65 | + |
| 66 | + /// <summary> |
| 67 | + /// Writes log events to a SharpCoreDB database using a connection string. |
| 68 | + /// </summary> |
| 69 | + /// <param name="loggerSinkConfiguration">The logger sink configuration.</param> |
| 70 | + /// <param name="path">The path to the .scdb file.</param> |
| 71 | + /// <param name="password">The encryption password for the database.</param> |
| 72 | + /// <param name="tableName">The name of the table to write logs to (default: "Logs").</param> |
| 73 | + /// <param name="restrictedToMinimumLevel">The minimum log level (default: Verbose).</param> |
| 74 | + /// <param name="batchPostingLimit">The maximum number of events to include in a single batch (default: 50).</param> |
| 75 | + /// <param name="period">The time to wait between checking for event batches (default: 2 seconds).</param> |
| 76 | + /// <param name="autoCreateTable">Whether to automatically create the table if it doesn't exist (default: true).</param> |
| 77 | + /// <param name="storageEngine">The storage engine to use (default: "AppendOnly").</param> |
| 78 | + /// <param name="serviceProvider">Optional service provider for resolving dependencies. If null, creates a new instance.</param> |
| 79 | + /// <returns>Logger configuration, allowing chaining.</returns> |
| 80 | + public static LoggerConfiguration SharpCoreDB( |
| 81 | + this LoggerSinkConfiguration loggerSinkConfiguration, |
| 82 | + string path, |
| 83 | + string password, |
| 84 | + string tableName = "Logs", |
| 85 | + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, |
| 86 | + int batchPostingLimit = DefaultBatchPostingLimit, |
| 87 | + TimeSpan? period = null, |
| 88 | + bool autoCreateTable = true, |
| 89 | + string storageEngine = "AppendOnly", |
| 90 | + IServiceProvider? serviceProvider = null) |
| 91 | + { |
| 92 | + ArgumentNullException.ThrowIfNull(loggerSinkConfiguration); |
| 93 | + |
| 94 | + if (string.IsNullOrWhiteSpace(path)) |
| 95 | + { |
| 96 | + throw new ArgumentException("Path cannot be null or whitespace.", nameof(path)); |
| 97 | + } |
| 98 | + |
| 99 | + if (string.IsNullOrWhiteSpace(password)) |
| 100 | + { |
| 101 | + throw new ArgumentException("Password cannot be null or whitespace.", nameof(password)); |
| 102 | + } |
| 103 | + |
| 104 | + // Create or use provided service provider |
| 105 | + var services = serviceProvider ?? CreateDefaultServiceProvider(); |
| 106 | + var factory = services.GetRequiredService<DatabaseFactory>(); |
| 107 | + |
| 108 | + // Create database with optimized config for logging |
| 109 | + var config = new DatabaseConfig |
| 110 | + { |
| 111 | + EnableQueryCache = false, // Logs are typically write-once |
| 112 | + EnablePageCache = true, |
| 113 | + PageCacheCapacity = 1024, |
| 114 | + UseGroupCommitWal = true, |
| 115 | + WalDurabilityMode = DurabilityMode.Async, |
| 116 | + WalMaxBatchSize = batchPostingLimit, |
| 117 | + WalMaxBatchDelayMs = (int)period.GetValueOrDefault(DefaultPeriod).TotalMilliseconds |
| 118 | + }; |
| 119 | + |
| 120 | + var database = factory.Create(path, password, isReadOnly: false, config: config); |
| 121 | + |
| 122 | + return SharpCoreDB( |
| 123 | + loggerSinkConfiguration, |
| 124 | + database, |
| 125 | + tableName, |
| 126 | + restrictedToMinimumLevel, |
| 127 | + batchPostingLimit, |
| 128 | + period, |
| 129 | + autoCreateTable, |
| 130 | + storageEngine); |
| 131 | + } |
| 132 | + |
| 133 | + /// <summary> |
| 134 | + /// Writes log events to a SharpCoreDB database using options. |
| 135 | + /// </summary> |
| 136 | + /// <param name="loggerSinkConfiguration">The logger sink configuration.</param> |
| 137 | + /// <param name="options">The sink options.</param> |
| 138 | + /// <returns>Logger configuration, allowing chaining.</returns> |
| 139 | + public static LoggerConfiguration SharpCoreDB( |
| 140 | + this LoggerSinkConfiguration loggerSinkConfiguration, |
| 141 | + SharpCoreDBSinkOptions options) |
| 142 | + { |
| 143 | + ArgumentNullException.ThrowIfNull(loggerSinkConfiguration); |
| 144 | + |
| 145 | + ArgumentNullException.ThrowIfNull(options); |
| 146 | + |
| 147 | + if (options.Database != null) |
| 148 | + { |
| 149 | + return SharpCoreDB( |
| 150 | + loggerSinkConfiguration, |
| 151 | + options.Database, |
| 152 | + options.TableName, |
| 153 | + options.RestrictedToMinimumLevel, |
| 154 | + options.BatchPostingLimit, |
| 155 | + options.Period, |
| 156 | + options.AutoCreateTable, |
| 157 | + options.StorageEngine); |
| 158 | + } |
| 159 | + |
| 160 | + if (!string.IsNullOrWhiteSpace(options.Path)) |
| 161 | + { |
| 162 | + return SharpCoreDB( |
| 163 | + loggerSinkConfiguration, |
| 164 | + options.Path, |
| 165 | + options.Password ?? string.Empty, |
| 166 | + options.TableName, |
| 167 | + options.RestrictedToMinimumLevel, |
| 168 | + options.BatchPostingLimit, |
| 169 | + options.Period, |
| 170 | + options.AutoCreateTable, |
| 171 | + options.StorageEngine, |
| 172 | + options.ServiceProvider); |
| 173 | + } |
| 174 | + |
| 175 | + throw new ArgumentException("Either Database or Path must be specified in options.", nameof(options)); |
| 176 | + } |
| 177 | + |
| 178 | + private static IServiceProvider CreateDefaultServiceProvider() |
| 179 | + { |
| 180 | + var services = new ServiceCollection(); |
| 181 | + services.AddSharpCoreDB(); |
| 182 | + return services.BuildServiceProvider(); |
| 183 | + } |
| 184 | +} |
0 commit comments