Example #1
0
 public SinkDependenciesFactoryTests()
 {
     _sinkOptions = new MSSqlServerSinkOptions {
         TableName = "LogEvents"
     };
     _columnOptions = new Serilog.Sinks.MSSqlServer.ColumnOptions();
 }
        public MSSqlServerAuditSinkTests()
        {
            _sinkOptions = new MSSqlServerSinkOptions
            {
                TableName  = _tableName,
                SchemaName = _schemaName
            };

            _columnOptions = new Serilog.Sinks.MSSqlServer.ColumnOptions();

            _dataTable            = new DataTable(_tableName);
            _dataTableCreatorMock = new Mock <IDataTableCreator>();
            _dataTableCreatorMock.Setup(d => d.CreateDataTable())
            .Returns(_dataTable);

            _sqlTableCreatorMock = new Mock <ISqlTableCreator>();
            _sqlLogEventWriter   = new Mock <ISqlLogEventWriter>();

            _sinkDependencies = new SinkDependencies
            {
                DataTableCreator  = _dataTableCreatorMock.Object,
                SqlTableCreator   = _sqlTableCreatorMock.Object,
                SqlLogEventWriter = _sqlLogEventWriter.Object
            };
        }
        public static LoggerConfiguration MSSqlServer(
            this LoggerSinkConfiguration loggerConfiguration,
            string connectionString,
            string tableName,
            IConfiguration appConfiguration        = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit                      = MSSqlServerSink.DefaultBatchPostingLimit,
            TimeSpan?period                            = null,
            IFormatProvider formatProvider             = null,
            bool autoCreateSqlTable                    = false,
            ColumnOptions columnOptions                = null,
            IConfigurationSection columnOptionsSection = null,
            string schemaName                          = MSSqlServerSink.DefaultSchemaName,
            ITextFormatter logEventFormatter           = null)
        {
            // Do not add new parameters here. This interface is considered legacy and will be deprecated in the future.
            // For adding new input parameters use the MSSqlServerSinkOptions class and the method overload that accepts MSSqlServerSinkOptions.

            var sinkOptions = new MSSqlServerSinkOptions(tableName, batchPostingLimit, period, autoCreateSqlTable, schemaName);

            return(loggerConfiguration.MSSqlServer(
                       connectionString: connectionString,
                       sinkOptions: sinkOptions,
                       sinkOptionsSection: null,
                       appConfiguration: appConfiguration,
                       restrictedToMinimumLevel: restrictedToMinimumLevel,
                       formatProvider: formatProvider,
                       columnOptions: columnOptions,
                       columnOptionsSection: columnOptionsSection,
                       logEventFormatter: logEventFormatter));
        }
 private static void ReadTableOptions(MSSqlServerConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
 {
     SetProperty.IfProvided <string>(config.TableName, nameof(config.TableName.Value), value => sinkOptions.TableName    = value);
     SetProperty.IfProvided <string>(config.SchemaName, nameof(config.SchemaName.Value), value => sinkOptions.SchemaName = value);
     SetProperty.IfProvided <bool>(config.AutoCreateSqlTable, nameof(config.AutoCreateSqlTable.Value),
                                   value => sinkOptions.AutoCreateSqlTable = value);
 }
        public void MSSqlServerAuditCallsSinkFactoryWithSuppliedParameters()
        {
            // Arrange
            var sinkOptions = new MSSqlServerSinkOptions {
                TableName = "TestTableName"
            };
            var columnOptions         = new Serilog.Sinks.MSSqlServer.ColumnOptions();
            var formatProviderMock    = new Mock <IFormatProvider>();
            var logEventFormatterMock = new Mock <ITextFormatter>();

            var auditSinkFactoryMock = new Mock <IMSSqlServerAuditSinkFactory>();

            // Act
            _loggerConfiguration.AuditTo.MSSqlServerInternal(
                configSectionName: "TestConfigSectionName",
                connectionString: "TestConnectionString",
                sinkOptions: sinkOptions,
                restrictedToMinimumLevel: LevelAlias.Minimum,
                formatProvider: formatProviderMock.Object,
                columnOptions: columnOptions,
                logEventFormatter: logEventFormatterMock.Object,
                applySystemConfiguration: _applySystemConfigurationMock.Object,
                auditSinkFactory: auditSinkFactoryMock.Object);

            // Assert
            auditSinkFactoryMock.Verify(f => f.Create(It.IsAny <string>(), sinkOptions, formatProviderMock.Object,
                                                      columnOptions, logEventFormatterMock.Object), Times.Once);
        }
        // Internal overload with parameters used by tests to override the config section and inject mocks
        internal static LoggerConfiguration MSSqlServerInternal(
            this LoggerSinkConfiguration loggerConfiguration,
            string configSectionName,
            string connectionString,
            MSSqlServerSinkOptions sinkOptions,
            LogEventLevel restrictedToMinimumLevel,
            IFormatProvider formatProvider,
            ColumnOptions columnOptions,
            ITextFormatter logEventFormatter,
            IApplySystemConfiguration applySystemConfiguration,
            IMSSqlServerSinkFactory sinkFactory,
            IPeriodicBatchingSinkFactory batchingSinkFactory)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

            ReadConfiguration(configSectionName, ref connectionString, ref sinkOptions, ref columnOptions, applySystemConfiguration);

            var sink = sinkFactory.Create(connectionString, sinkOptions, formatProvider, columnOptions, logEventFormatter);

            var periodicBatchingSink = batchingSinkFactory.Create(sink, sinkOptions);

            return(loggerConfiguration.Sink(periodicBatchingSink, restrictedToMinimumLevel));
        }
        public void MSSqlServerAuditCallsApplySystemConfigurationGetSinkOptions()
        {
            // Arrange
            var sinkOptions         = new MSSqlServerSinkOptions();
            var systemConfigSection = new MSSqlServerConfigurationSection();

            _applySystemConfigurationMock.Setup(c => c.GetSinkConfigurationSection(It.IsAny <string>()))
            .Returns(systemConfigSection);
            var auditSinkFactoryMock = new Mock <IMSSqlServerAuditSinkFactory>();

            // Act
            _loggerConfiguration.AuditTo.MSSqlServerInternal(
                configSectionName: "TestConfigSectionName",
                connectionString: "TestConnectionString",
                sinkOptions: sinkOptions,
                restrictedToMinimumLevel: LevelAlias.Minimum,
                formatProvider: null,
                columnOptions: new Serilog.Sinks.MSSqlServer.ColumnOptions(),
                logEventFormatter: null,
                applySystemConfiguration: _applySystemConfigurationMock.Object,
                auditSinkFactory: auditSinkFactoryMock.Object);

            // Assert
            _applySystemConfigurationMock.Verify(c => c.ConfigureSinkOptions(systemConfigSection, sinkOptions),
                                                 Times.Once);
        }
        public void MSSqlServerAuditCallsSinkFactoryWithSinkOptionsFromSystemConfig()
        {
            // Arrange
            var configSinkOptions = new MSSqlServerSinkOptions();

            _applySystemConfigurationMock.Setup(c => c.GetSinkConfigurationSection(It.IsAny <string>()))
            .Returns(new MSSqlServerConfigurationSection());
            _applySystemConfigurationMock.Setup(c => c.ConfigureSinkOptions(It.IsAny <MSSqlServerConfigurationSection>(), It.IsAny <MSSqlServerSinkOptions>()))
            .Returns(configSinkOptions);
            var auditSinkFactoryMock = new Mock <IMSSqlServerAuditSinkFactory>();

            // Act
            _loggerConfiguration.AuditTo.MSSqlServerInternal(
                configSectionName: "TestConfigSectionName",
                connectionString: "TestConnectionString",
                sinkOptions: new MSSqlServerSinkOptions {
                TableName = "TestTableName"
            },
                restrictedToMinimumLevel: LevelAlias.Minimum,
                formatProvider: null,
                columnOptions: new Serilog.Sinks.MSSqlServer.ColumnOptions(),
                logEventFormatter: null,
                applySystemConfiguration: _applySystemConfigurationMock.Object,
                auditSinkFactory: auditSinkFactoryMock.Object);

            // Assert
            auditSinkFactoryMock.Verify(f => f.Create(It.IsAny <string>(), configSinkOptions, It.IsAny <IFormatProvider>(),
                                                      It.IsAny <Serilog.Sinks.MSSqlServer.ColumnOptions>(), It.IsAny <ITextFormatter>()), Times.Once);
        }
        public void MSSqlServerCallsSinkFactoryWithSuppliedParameters()
        {
            // Arrange
            var sinkOptions = new MSSqlServerSinkOptions {
                TableName = "TestTableName"
            };
            var columnOptions                   = new Serilog.Sinks.MSSqlServer.ColumnOptions();
            var formatProviderMock              = new Mock <IFormatProvider>();
            var logEventFormatterMock           = new Mock <ITextFormatter>();
            var sinkFactoryMock                 = new Mock <IMSSqlServerSinkFactory>();
            var periodicBatchingSinkFactoryMock = new Mock <IPeriodicBatchingSinkFactory>();

            periodicBatchingSinkFactoryMock.Setup(f => f.Create(It.IsAny <MSSqlServerSink>(), It.IsAny <MSSqlServerSinkOptions>()))
            .Returns(new Mock <ILogEventSink>().Object);
            _applySystemConfigurationMock.Setup(c => c.GetConnectionString(It.IsAny <string>()))
            .Returns <string>(c => c);

            // Act
            _loggerConfiguration.WriteTo.MSSqlServerInternal(
                configSectionName: "TestConfigSectionName",
                connectionString: "TestConnectionString",
                sinkOptions: sinkOptions,
                restrictedToMinimumLevel: LevelAlias.Minimum,
                formatProvider: formatProviderMock.Object,
                columnOptions: columnOptions,
                logEventFormatter: logEventFormatterMock.Object,
                applySystemConfiguration: _applySystemConfigurationMock.Object,
                sinkFactory: sinkFactoryMock.Object,
                batchingSinkFactory: periodicBatchingSinkFactoryMock.Object);

            // Assert
            sinkFactoryMock.Verify(f => f.Create(It.IsAny <string>(), sinkOptions, formatProviderMock.Object,
                                                 columnOptions, logEventFormatterMock.Object), Times.Once);
        }
        public void MSSqlServerCallsBatchedSinkFactoryWithSinkFromSinkFactoryAndSuppliedSinkOptions()
        {
            // Arrange
            var sinkOptions     = new MSSqlServerSinkOptions();
            var sinkMock        = new Mock <IBatchedLogEventSink>();
            var sinkFactoryMock = new Mock <IMSSqlServerSinkFactory>();
            var periodicBatchingSinkFactoryMock = new Mock <IPeriodicBatchingSinkFactory>();

            sinkFactoryMock.Setup(f => f.Create(It.IsAny <string>(), It.IsAny <MSSqlServerSinkOptions>(), It.IsAny <IFormatProvider>(),
                                                It.IsAny <MSSqlServer.ColumnOptions>(), It.IsAny <ITextFormatter>()))
            .Returns(sinkMock.Object);

            // Act
            _loggerConfiguration.WriteTo.MSSqlServerInternal(
                configSectionName: "TestConfigSectionName",
                connectionString: "TestConnectionString",
                sinkOptions: sinkOptions,
                restrictedToMinimumLevel: LevelAlias.Minimum,
                formatProvider: null,
                columnOptions: null,
                logEventFormatter: null,
                applySystemConfiguration: _applySystemConfigurationMock.Object,
                sinkFactory: sinkFactoryMock.Object,
                batchingSinkFactory: periodicBatchingSinkFactoryMock.Object);

            // Assert
            periodicBatchingSinkFactoryMock.Verify(f => f.Create(sinkMock.Object, sinkOptions), Times.Once);
        }
        // Internal overload with parameters used by tests to override the config section and inject mocks
        internal static LoggerConfiguration MSSqlServerInternal(
            this LoggerAuditSinkConfiguration loggerAuditSinkConfiguration,
            string connectionString,
            MSSqlServerSinkOptions sinkOptions,
            IConfigurationSection sinkOptionsSection,
            IConfiguration appConfiguration,
            LogEventLevel restrictedToMinimumLevel,
            IFormatProvider formatProvider,
            ColumnOptions columnOptions,
            IConfigurationSection columnOptionsSection,
            ITextFormatter logEventFormatter,
            IApplySystemConfiguration applySystemConfiguration,
            IApplyMicrosoftExtensionsConfiguration applyMicrosoftExtensionsConfiguration,
            IMSSqlServerAuditSinkFactory auditSinkFactory)
        {
            if (loggerAuditSinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerAuditSinkConfiguration));
            }

            ReadConfiguration(ref connectionString, ref sinkOptions, sinkOptionsSection, appConfiguration,
                              ref columnOptions, columnOptionsSection, applySystemConfiguration, applyMicrosoftExtensionsConfiguration);

            var auditSink = auditSinkFactory.Create(connectionString, sinkOptions, formatProvider, columnOptions, logEventFormatter);

            return(loggerAuditSinkConfiguration.Sink(auditSink, restrictedToMinimumLevel));
        }
 private static void ReadTableOptions(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
 {
     SetProperty.IfNotNull <string>(config["tableName"], val => sinkOptions.TableName   = val);
     SetProperty.IfNotNull <string>(config["schemaName"], val => sinkOptions.SchemaName = val);
     SetProperty.IfNotNull <bool>(config["autoCreateSqlTable"], val => sinkOptions.AutoCreateSqlTable   = val);
     SetProperty.IfNotNull <bool>(config["enlistInTransaction"], val => sinkOptions.EnlistInTransaction = val);
 }
        /// <summary>
        /// Adds a sink that writes log events to a table in a MSSqlServer database.
        /// </summary>
        /// <param name="loggerAuditSinkConfiguration">The logger configuration.</param>
        /// <param name="connectionString">The connection string to the database where to store the events.</param>
        /// <param name="sinkOptions">Supplies additional settings for the sink</param>
        /// <param name="sinkOptionsSection">A config section defining additional settings for the sink</param>
        /// <param name="appConfiguration">Additional application-level configuration. Required if connectionString is a name.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="columnOptions">An externally-modified group of column settings</param>
        /// <param name="columnOptionsSection">A config section defining various column settings</param>
        /// <param name="logEventFormatter">Supplies custom formatter for the LogEvent column, or null</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration MSSqlServer(
            this LoggerAuditSinkConfiguration loggerAuditSinkConfiguration,
            string connectionString,
            MSSqlServerSinkOptions sinkOptions       = null,
            IConfigurationSection sinkOptionsSection = null,
            IConfiguration appConfiguration          = null,
            LogEventLevel restrictedToMinimumLevel   = LevelAlias.Minimum,
            IFormatProvider formatProvider           = null,
            ColumnOptions columnOptions = null,
            IConfigurationSection columnOptionsSection = null,
            ITextFormatter logEventFormatter           = null)
        {
            if (loggerAuditSinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerAuditSinkConfiguration));
            }

            ReadConfiguration(ref connectionString, ref sinkOptions, appConfiguration, ref columnOptions,
                              columnOptionsSection, sinkOptionsSection);

            IMSSqlServerAuditSinkFactory auditSinkFactory = new MSSqlServerAuditSinkFactory();
            var auditSink = auditSinkFactory.Create(connectionString, sinkOptions, formatProvider, columnOptions, logEventFormatter);

            return(loggerAuditSinkConfiguration.Sink(auditSink, restrictedToMinimumLevel));
        }
 /// <summary>
 /// Adds a sink that writes log events to a table in a MSSqlServer database.
 /// Create a database and execute the table creation script found here
 /// https://gist.github.com/mivano/10429656
 /// or use the autoCreateSqlTable option.
 /// </summary>
 /// <param name="loggerConfiguration">The logger configuration.</param>
 /// <param name="connectionString">The connection string to the database where to store the events.</param>
 /// <param name="sinkOptions">Supplies additional settings for the sink</param>
 /// <param name="sinkOptionsSection">A config section defining additional settings for the sink</param>
 /// <param name="appConfiguration">Additional application-level configuration. Required if connectionString is a name.</param>
 /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
 /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
 /// <param name="columnOptions">An externally-modified group of column settings</param>
 /// <param name="columnOptionsSection">A config section defining various column settings</param>
 /// <param name="logEventFormatter">Supplies custom formatter for the LogEvent column, or null</param>
 /// <returns>Logger configuration, allowing configuration to continue.</returns>
 /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
 public static LoggerConfiguration MSSqlServer(
     this LoggerSinkConfiguration loggerConfiguration,
     string connectionString,
     MSSqlServerSinkOptions sinkOptions       = null,
     IConfigurationSection sinkOptionsSection = null,
     IConfiguration appConfiguration          = null,
     LogEventLevel restrictedToMinimumLevel   = LevelAlias.Minimum,
     IFormatProvider formatProvider           = null,
     ColumnOptions columnOptions = null,
     IConfigurationSection columnOptionsSection = null,
     ITextFormatter logEventFormatter           = null) =>
 loggerConfiguration.MSSqlServerInternal(
     connectionString: connectionString,
     sinkOptions: sinkOptions,
     sinkOptionsSection: sinkOptionsSection,
     appConfiguration: appConfiguration,
     restrictedToMinimumLevel: restrictedToMinimumLevel,
     formatProvider: formatProvider,
     columnOptions: columnOptions,
     columnOptionsSection: columnOptionsSection,
     logEventFormatter: logEventFormatter,
     applySystemConfiguration: new ApplySystemConfiguration(),
     applyMicrosoftExtensionsConfiguration: new ApplyMicrosoftExtensionsConfiguration(),
     sinkFactory: new MSSqlServerSinkFactory(),
     batchingSinkFactory: new PeriodicBatchingSinkFactory());
Example #15
0
        public static void Main(string[] args)
        {
            var sinkOpts = new MSSqlServerSinkOptions();

            sinkOpts.TableName = "Logs";
            var columnOpts = new ColumnOptions();

            columnOpts.Store.Remove(StandardColumn.Properties);
            columnOpts.Store.Add(StandardColumn.LogEvent);
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .WriteTo.MSSqlServer(connectionString: "",
                                              sinkOptions: sinkOpts)
                         .CreateLogger();

            try
            {
                Log.Information("Starting Web Host");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        private static MSSqlServerSinkOptions GetMSSqlServerSinkOptions()
        {
            var options = new MSSqlServerSinkOptions();

            options.AutoCreateSqlTable = true;
            options.TableName          = "Logs";
            return(options);
        }
Example #17
0
        public static void AddLoggerLayer(this IServiceCollection services, IConfiguration configuration)
        {
            //პროექტის გაშვებამდე ლოგის შესაქმნელად:

            /*            var appSettings = new ConfigurationBuilder()
             *              .SetBasePath(Directory.GetCurrentDirectory())
             *              .AddJsonFile("appsettings.json")
             *              .Build();*/


            var logDB = configuration.GetConnectionString("DefaultConnection");


            var sinkOpts = new MSSqlServerSinkOptions
            {
                TableName          = "LogEvents",
                SchemaName         = "dbo",
                AutoCreateSqlTable = true,
                BatchPostingLimit  = 1000,
                BatchPeriod        = new TimeSpan(0, 0, 10)
            };

            var columnOpts = new ColumnOptions()
            {
                AdditionalColumns = new Collection <SqlColumn>
                {
                    new SqlColumn
                    {
                        ColumnName        = "AccountType",
                        PropertyName      = "AccountType",
                        DataType          = SqlDbType.NVarChar,
                        DataLength        = 32,
                        NonClusteredIndex = false,
                        AllowNull         = true
                    },
                    new SqlColumn
                    {
                        ColumnName        = "AccountId",
                        DataType          = SqlDbType.UniqueIdentifier,
                        NonClusteredIndex = true,
                        AllowNull         = true
                    }
                }
            };

            // we don't need XML data
            //columnOpts.Store.Remove(StandardColumn.Properties);
            // we do want JSON data
            columnOpts.Store.Add(StandardColumn.LogEvent);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .WriteTo.MSSqlServer(
                connectionString: logDB,
                sinkOptions: sinkOpts,
                columnOptions: columnOpts)
                         .CreateLogger();
        }
        private static MSSqlServerSinkOptions GetMSSqlServerSinkOptions2()
        {
            // ONLY LOGS with ErrorId property will be logged
            var options = new MSSqlServerSinkOptions();

            options.AutoCreateSqlTable = true;
            options.TableName          = "LogsWithFilter";
            return(options);
        }
        public void InitializesDefaultedPropertiesWithDefaultsWhenCalledWithParameters()
        {
            // Act
            var sut = new MSSqlServerSinkOptions("TestTableName", null, null, true, null);

            // Assert
            Assert.Equal(MSSqlServerSink.DefaultSchemaName, sut.SchemaName);
            Assert.Equal(MSSqlServerSink.DefaultBatchPostingLimit, sut.BatchPostingLimit);
            Assert.Equal(MSSqlServerSink.DefaultPeriod, sut.BatchPeriod);
        }
Example #20
0
        public ILogEventSink Create(IBatchedLogEventSink sink, MSSqlServerSinkOptions sinkOptions)
        {
            var periodicBatchingSinkOptions = new PeriodicBatchingSinkOptions
            {
                BatchSizeLimit        = sinkOptions.BatchPostingLimit,
                Period                = sinkOptions.BatchPeriod,
                EagerlyEmitFirstEvent = sinkOptions.EagerlyEmitFirstEvent
            };

            return(new PeriodicBatchingSink(sink, periodicBatchingSinkOptions));
        }
 public ILogEventSink Create(
     string connectionString,
     MSSqlServerSinkOptions sinkOptions,
     IFormatProvider formatProvider,
     ColumnOptions columnOptions,
     ITextFormatter logEventFormatter) =>
 new MSSqlServerAuditSink(
     connectionString,
     sinkOptions,
     formatProvider,
     columnOptions,
     logEventFormatter);
Example #22
0
        public MSSqlServerSinkOptions ConfigureSinkOptions(MSSqlServerSinkOptions sinkOptions, IConfigurationSection config)
        {
            if (config == null)
            {
                return(sinkOptions);
            }

            ReadTableOptions(config, sinkOptions);
            ReadBatchSettings(config, sinkOptions);
            ReadAzureManagedIdentitiesOptions(config, sinkOptions);

            return(sinkOptions);
        }
        public void InitializeWithDisableTriggersThrows()
        {
            // Arrange
            var sinkOptions = new MSSqlServerSinkOptions {
                TableName = "TestTableName"
            };
            var columnOptions = new Serilog.Sinks.MSSqlServer.ColumnOptions {
                DisableTriggers = true
            };

            // Act + assert
            Assert.Throws <NotSupportedException>(() =>
                                                  new MSSqlServerAuditSink(sinkOptions, columnOptions, _sinkDependencies));
        }
        public DatabaseLogger()
        {
            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            var sinkOpts = new MSSqlServerSinkOptions {
                TableName = "Logs", AutoCreateSqlTable = true
            };

            var seriLogConfig = new LoggerConfiguration()
                                .ReadFrom.Configuration(configuration)
                                .CreateLogger();

            Logger = seriLogConfig;
        }
Example #25
0
        public void MSSqlServerSinkFactoryCreateReturnsInstance()
        {
            // Arrange
            var sinkOptions = new MSSqlServerSinkOptions {
                TableName = "TestTableName"
            };
            var sut = new MSSqlServerSinkFactory();

            // Act
            var result = sut.Create(DatabaseFixture.LogEventsConnectionString, sinkOptions, null, new MSSqlServer.ColumnOptions(), null);

            // Assert
            Assert.IsType <MSSqlServerSink>(result);
        }
        public void ConfigureSinkOptionsCalledWithConfigSectionNullReturnsUnchangedSinkOptions()
        {
            // Arrange
            var sinkOptions = new MSSqlServerSinkOptions {
                UseAzureManagedIdentity = true
            };
            var sut = new MicrosoftExtensionsSinkOptionsProvider();

            // Act
            var result = sut.ConfigureSinkOptions(sinkOptions, null);

            // Assert
            Assert.True(result.UseAzureManagedIdentity);
        }
Example #27
0
        private static MSSqlServerSinkOptions BuildSinkOptions(DbLoggingConfig dbLoggingConfig)
        {
            var batchPeriod = TimeSpan.FromSeconds(dbLoggingConfig.BatchPeriodSecs > 0 ? dbLoggingConfig.BatchPeriodSecs : 5);
            var schemaName  = dbLoggingConfig.SchemaName ?? "dbo";
            var sinkOptions = new MSSqlServerSinkOptions
            {
                TableName          = "Logs",
                SchemaName         = schemaName,
                AutoCreateSqlTable = false,
                BatchPostingLimit  = 1000,
                BatchPeriod        = batchPeriod
            };

            return(sinkOptions);
        }
        public static IHostBuilder ConfigureSerilog(this IHostBuilder builder)
        {
            builder
            .ConfigureLogging((context, logging) => { logging.ClearProviders(); })
            .UseSerilog((hostingContext, loggerConfiguration) =>
            {
                var config                      = hostingContext.Configuration;
                var connectionString            = config.GetConnectionString("AutoLot").ToString();
                var tableName                   = config["Logging:MSSqlServer:tableName"].ToString();
                var schema                      = config["Logging:MSSqlServer:schema"].ToString();
                string restrictedToMinimumLevel =
                    config["Logging:MSSqlServer:restrictedToMinimumLevel"].ToString();
                //LogEventLevel logLevel = log;
                if (!Enum.TryParse <LogEventLevel>(restrictedToMinimumLevel, out var logLevel))
                {
                    logLevel = LogEventLevel.Debug;
                }
                LogEventLevel level = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), restrictedToMinimumLevel);
                var sqlOptions      = new MSSqlServerSinkOptions
                {
                    AutoCreateSqlTable = false,
                    SchemaName         = schema,
                    TableName          = tableName,
                };
                if (hostingContext.HostingEnvironment.IsDevelopment())
                {
                    sqlOptions.BatchPeriod       = new TimeSpan(0, 0, 0, 1);
                    sqlOptions.BatchPostingLimit = 1;
                }

                loggerConfiguration
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                //.ReadFrom.Configuration(hostingContext.Configuration)
                .WriteTo.File(
                    path: "ErrorLog.txt",
                    rollingInterval: RollingInterval.Day,
                    restrictedToMinimumLevel: logLevel,
                    outputTemplate: OutputTemplate)
                .WriteTo.Console(restrictedToMinimumLevel: logLevel)
                .WriteTo.MSSqlServer(
                    connectionString: connectionString,
                    sqlOptions,
                    restrictedToMinimumLevel: level,
                    columnOptions: ColumnOptions);
            });
            return(builder);
        }
Example #29
0
        public MsSqlLogger()
        {
            IConfiguration configuration = ServiceTool.ServiceProvider.GetService <IConfiguration>();

            var logConfig = configuration.GetSection("SeriLogConfigurations:MsSqlConfiguration")
                            .Get <MsSqlConfiguration>() ?? throw new Exception(Utilities.Messages.SerilogMessages.NullOptionsMessage);
            var sinkOpts = new MSSqlServerSinkOptions {
                TableName = "Logs", AutoCreateSqlTable = true
            };

            var seriLogConfig = new LoggerConfiguration()
                                .WriteTo.MSSqlServer(connectionString: logConfig.ConnectionString, sinkOptions: sinkOpts)
                                .CreateLogger();

            _logger = seriLogConfig;
        }
        private static void ReadConfiguration(
            ref string connectionString,
            ref MSSqlServerSinkOptions sinkOptions,
            IConfiguration appConfiguration,
            ref ColumnOptions columnOptions,
            IConfigurationSection columnOptionsSection,
            IConfigurationSection sinkOptionsSection)
        {
            sinkOptions   = sinkOptions ?? new MSSqlServerSinkOptions();
            columnOptions = columnOptions ?? new ColumnOptions();

            IApplyMicrosoftExtensionsConfiguration microsoftExtensionsConfiguration = new ApplyMicrosoftExtensionsConfiguration();

            connectionString = microsoftExtensionsConfiguration.GetConnectionString(connectionString, appConfiguration);
            columnOptions    = microsoftExtensionsConfiguration.ConfigureColumnOptions(columnOptions, columnOptionsSection);
            sinkOptions      = microsoftExtensionsConfiguration.ConfigureSinkOptions(sinkOptions, sinkOptionsSection);
        }