示例#1
0
        public ColumnConfig(ColumnOptions columnOptions = null)
        {
            if (columnOptions == null)
            {
                return;
            }

            width = columnOptions.Width.HasValue ? columnOptions.Width.ToString() : "auto";
            header = columnOptions.Header;
            dataIndex = columnOptions.Id;
        }
示例#2
0
        private ILogger CreateLogger(ISettings settings, string fileName = null, string tableName = null, ICollection <DataColumn> additionalColumns = null, bool?logToFile = null, bool?logToSql = null)
        {
            var logsPath = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"))
                ? HostingEnvironment.ApplicationPhysicalPath
                : Path.Combine(Environment.GetEnvironmentVariable("HOME"), "LogFiles");

            var logger = new LoggerConfiguration()
                         .Enrich.With <HttpRequestIdEnricher>()
                         .Enrich.With <UserNameEnricher>()
                         .Enrich.With <EventIdEnricher>();

            if (logToFile ?? settings.LogToFile && !string.IsNullOrEmpty(fileName))
            {
                logger = logger.WriteTo.RollingFile(Path.Combine(logsPath, fileName), fileSizeLimitBytes: null);
            }

            if (logToSql ?? settings.LogToSql &&
                !string.IsNullOrEmpty(settings.LoggingSqlServerConnectionString) &&
                !string.IsNullOrEmpty(tableName))
            {
                var columnOptions = new ColumnOptions
                {
                    AdditionalDataColumns = new Collection <DataColumn>
                    {
                        new DataColumn {
                            DataType = typeof(string), ColumnName = "UserName"
                        },
                        new DataColumn {
                            DataType = typeof(string), ColumnName = "HttpRequestId"
                        },
                        new DataColumn {
                            DataType = typeof(int), ColumnName = "EventId"
                        }
                    }
                    .Union(additionalColumns ?? Enumerable.Empty <DataColumn>())
                    .ToList()
                };
                logger = logger.WriteTo.MSSqlServer(settings.LoggingSqlServerConnectionString, tableName, restrictedToMinimumLevel: LogEventLevel.Information, columnOptions: columnOptions);
            }
            return(logger.CreateLogger());
        }
示例#3
0
        protected void setExcelRange <T>(T value, Position pos, ColumnOptions options)
        {
            using (var range = _ws.Cells[pos.Row, pos.Col, pos.Row + options.Rowspan - 1, pos.Col + options.Colspan - 1])
            {
                range.Merge = options.Colspan > 1 || options.Rowspan > 1;
                if (!string.IsNullOrEmpty(options.Formula))
                {
                    range.Formula = options.Formula;
                }
                else
                {
                    range.Value = value;
                }

                if (options.Width.HasValue)
                {
                    _ws.Column(pos.Col).Width = options.Width.Value;
                }

                range.Style.WrapText            = true;
                range.Style.HorizontalAlignment = options.HorizontalAlignment.ToEPPlusHorizontalAligment();
                range.Style.VerticalAlignment   = options.VerticalAlignment.ToEpPlusVerticalAlignment();

                // border
                range.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);

                if (options.VerticalText)
                {
                    range.Style.TextRotation = 90;
                }

                range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                range.Style.Font.Color.SetColor(options.TextColor);
                range.Style.Fill.BackgroundColor.SetColor(options.BackgroundColor);

                //////MeasureTextHeight(value.ToString(), range.Style.Font, options.Colspan);
                //////_ws.Column(pos.Col).Width = Math.Min(size.width * 72.0 / 96.0, 409);
                //var size = measureText(value?.ToString() , range.Style.Font, options.Colspan);// * 72.0 / 96.0;
                //_ws.Row(pos.Row).Height = size.height; //Math.Min(size.height * 72.0 / 96.0, 409);
            }
        }
示例#4
0
        public void WriteEventToCustomStandardColumns()
        {
            // arrange
            var options = new ColumnOptions();

            options.Message.ColumnName         = "CustomMessage";
            options.MessageTemplate.ColumnName = "CustomMessageTemplate";
            options.Level.ColumnName           = "CustomLevel";
            options.TimeStamp.ColumnName       = "CustomTimeStamp";
            options.Exception.ColumnName       = "CustomException";
            options.Properties.ColumnName      = "CustomProperties";
            options.Id.ColumnName = "CustomId";

            var logTableName        = $"{DatabaseFixture.LogTableName}CustomEvent";
            var loggerConfiguration = new LoggerConfiguration();

            Log.Logger = loggerConfiguration.WriteTo.MSSqlServer(
                connectionString: DatabaseFixture.LogEventsConnectionString,
                tableName: logTableName,
                autoCreateSqlTable: true,
                columnOptions: options)
                         .CreateLogger();

            var file = File.CreateText("CustomColumnsEvent.Self.log");

            Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));

            // act
            const string loggingInformationMessage = "Logging Information message";

            Log.Information(loggingInformationMessage);
            Log.CloseAndFlush();

            // assert
            using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
            {
                var logEvents = conn.Query <CustomStandardLogColumns>($"SELECT * FROM {logTableName}");

                logEvents.Should().Contain(e => e.CustomMessage.Contains(loggingInformationMessage));
            }
        }
        /// <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="tableName">Name of the table to store the events in.</param>
        /// <param name="schemaName">Name of the schema for the table to store the data in. The default is 'dbo'.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="autoCreateSqlTable">Create log table with the provided name on destination sql server.</param>
        /// <param name="columnOptions"></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,
            string tableName,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit            = MSSqlServerSink.DefaultBatchPostingLimit,
            TimeSpan?period                  = null,
            IFormatProvider formatProvider   = null,
            bool autoCreateSqlTable          = false,
            ColumnOptions columnOptions      = null,
            string schemaName                = "dbo",
            ITextFormatter logEventFormatter = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

            var defaultedPeriod = period ?? MSSqlServerSink.DefaultPeriod;
            var colOpts         = columnOptions ?? new ColumnOptions();

            if (ConfigurationManager.GetSection(AppConfigSectionName) is MSSqlServerConfigurationSection serviceConfigSection)
            {
                colOpts = ApplySystemConfiguration.ConfigureColumnOptions(serviceConfigSection, colOpts);
            }

            connectionString = ApplySystemConfiguration.GetConnectionString(connectionString);

            return(loggerConfiguration.Sink(
                       new MSSqlServerSink(
                           connectionString,
                           tableName,
                           batchPostingLimit,
                           defaultedPeriod,
                           formatProvider,
                           autoCreateSqlTable,
                           colOpts,
                           schemaName,
                           logEventFormatter),
                       restrictedToMinimumLevel));
        }
        public void TestAuditOptionsDisableTriggersOnLogTableThrowsNotSupportedException()
        {
            // Arrange
            var options = new ColumnOptions {
                DisableTriggers = true
            };
            var loggerConfiguration = new LoggerConfiguration();

            Assert.Throws <NotSupportedException>(() => loggerConfiguration.AuditTo.MSSqlServer(
                                                      connectionString: DatabaseFixture.LogEventsConnectionString,
                                                      new SinkOptions
            {
                TableName          = DatabaseFixture.LogTableName,
                AutoCreateSqlTable = true
            },
                                                      columnOptions: options)
                                                  .CreateLogger());

            // throws, should be no table to delete unless the test fails
            DatabaseFixture.DropTable();
        }
示例#7
0
        public static void RegisterLogger(this IServiceCollection services, SerilogConfiguration serilogConfiguration)
        {
            var columnOptions = new ColumnOptions
            {
                AdditionalDataColumns = new Collection <DataColumn> {
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "StackTrace"
                    }
                }
            };

            columnOptions.Store.Remove(StandardColumn.MessageTemplate);
            columnOptions.Store.Remove(StandardColumn.Properties);

            Serilog.Log.Logger = new LoggerConfiguration()
                                 .WriteTo.MSSqlServer(serilogConfiguration.ConnectionString, serilogConfiguration.TableName, columnOptions: columnOptions,
                                                      restrictedToMinimumLevel: serilogConfiguration.MinimumLevel)
                                 .CreateLogger();
            services.AddSingleton <IPearUpLogger, PearUpLogger>();
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
        }
        public MsSqlLogger()
        {
            var 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 columnOpts = new ColumnOptions();

            columnOpts.Store.Remove(StandardColumn.Message);
            columnOpts.Store.Remove(StandardColumn.Properties);

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

            Logger = seriLogConfig;
        }
        public LoggerConfiguration ConfigSqlServer(LogEventLevel logEventLevel)
        {
            var ColumnOpt = new ColumnOptions();

            ColumnOpt.Store.Remove(StandardColumn.Properties);
            ColumnOpt.Store.Add(StandardColumn.LogEvent);
            ColumnOpt.LogEvent.DataLength         = -1;
            ColumnOpt.PrimaryKey                  = ColumnOpt.TimeStamp;
            ColumnOpt.TimeStamp.NonClusteredIndex = true;

            return(new LoggerConfiguration()
                   .Enrich.FromLogContext()
                   .MinimumLevel.Is(logEventLevel)
                   .WriteTo.MSSqlServer("Data Source=.;Initial Catalog=SerilogDB;Integrated Security=True;", new MSSqlServerSinkOptions
            {
                AutoCreateSqlTable = true,
                TableName = "tblPrancaBeautyLogs",
                BatchPeriod = new TimeSpan(0, 0, 1)
            },
                                        columnOptions: ColumnOpt));
        }
        public void LogEventExcludeStandardColumns()
        {
            // Arrange
            var columnOptions = new ColumnOptions();

            columnOptions.Store.Remove(StandardColumn.Properties);
            columnOptions.Store.Add(StandardColumn.LogEvent);
            columnOptions.LogEvent.ExcludeStandardColumns = true;

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer
                         (
                connectionString: DatabaseFixture.LogEventsConnectionString,
                new SinkOptions
            {
                TableName          = DatabaseFixture.LogTableName,
                AutoCreateSqlTable = true,
                BatchPostingLimit  = 1,
                BatchPeriod        = TimeSpan.FromSeconds(10)
            },
                columnOptions: columnOptions
                         )
                         .CreateLogger();

            // Act
            Log.Logger
            .ForContext("A", "AValue")
            .Information("Logging message");

            Log.CloseAndFlush();

            // Assert
            using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
            {
                var logEvents = conn.Query <LogEventColumn>($"SELECT LogEvent from {DatabaseFixture.LogTableName}");

                logEvents.Should().Contain(e => e.LogEvent.Contains("AValue"));
                logEvents.Should().NotContain(e => e.LogEvent.Contains("TimeStamp"));
            }
        }
示例#11
0
        void SearchControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= SearchControl_Loaded;

            if (DesignerProperties.GetIsInDesignMode(this) || QueryName == null)
            {
                return;
            }

            if (qd == null)
            {
                qd = DynamicQueryServer.GetQueryDescription(QueryName);
            }

            if (FilterColumn.HasText())
            {
                FilterOptions.Add(new FilterOption
                {
                    ColumnName = FilterColumn,
                    Operation  = FilterOperation.EqualTo,
                    Frozen     = true,
                }.Bind(FilterOption.ValueProperty, new Binding("DataContext" + (FilterRoute.HasText() ? "." + FilterRoute : null))
                {
                    Source = this
                }));
                ColumnOptions.Add(new ColumnOption(FilterColumn));
                ColumnOptionsMode = ColumnOptionsMode.Remove;
            }

            FilterOption.SetFilterTokens(FilterOptions, qd);

            AutomationProperties.SetName(this, QueryUtils.GetQueryUniqueKey(QueryName));

            Search();

            foreach (var item in FilterOptions)
            {
                item.BindingValueChanged += new DependencyPropertyChangedEventHandler(item_BindingValueChanged);
            }
        }
示例#12
0
        public static ColumnOptions Create()
        {
            var options = new ColumnOptions();

            options.Store.Remove(StandardColumn.MessageTemplate);
            options.Store.Remove(StandardColumn.Exception);

            options.AdditionalColumns = new Collection <SqlColumn>
            {
                new SqlColumn
                {
                    ColumnName        = "PerfItem", AllowNull = false,
                    DataType          = SqlDbType.NVarChar, DataLength = 100,
                    NonClusteredIndex = true
                },
                new SqlColumn
                {
                    ColumnName = "ElapsedMilliseconds", AllowNull = false,
                    DataType   = SqlDbType.Int
                },
                new SqlColumn
                {
                    ColumnName = "ActionName", AllowNull = false
                },
                new SqlColumn
                {
                    ColumnName = "MachineName", AllowNull = false
                },
                new SqlColumn
                {
                    ColumnName = "Assembly", AllowNull = false
                },
                new SqlColumn
                {
                    ColumnName = "RequestPath", AllowNull = false
                }
            };

            return(options);
        }
        public static void LogTimingToSqlServer(this LoggerConfiguration configuration, string connectionString, LogEventLevel minimumLevel)
        {
            var columnOptions = new ColumnOptions();

            columnOptions.Store.Remove(StandardColumn.MessageTemplate);
            columnOptions.Store.Remove(StandardColumn.Exception);
            columnOptions.Store.Remove(StandardColumn.Properties);
            columnOptions.Store.Add(StandardColumn.LogEvent);

            columnOptions.LogEvent.ExcludeAdditionalProperties = true;
            columnOptions.LogEvent.ExcludeStandardColumns      = true;
            //columnOptions.TimeStamp.ConvertToUtc = true;

            columnOptions.AdditionalColumns = new Collection <SqlColumn>
            {
                new SqlColumn {
                    ColumnName = "MethodName", DataType = SqlDbType.VarChar, DataLength = 300, AllowNull = false
                },
                new SqlColumn {
                    ColumnName = "ElapsedMilliSeconds", DataType = SqlDbType.BigInt, AllowNull = false, NonClusteredIndex = true
                },
                new SqlColumn {
                    ColumnName = "MethodHashCode", DataType = SqlDbType.BigInt, AllowNull = false, NonClusteredIndex = true
                },
                new SqlColumn {
                    ColumnName = "CorrelationId", DataType = SqlDbType.VarChar, DataLength = 36, NonClusteredIndex = true
                },
            };

            configuration.WriteTo.Logger(subLogger =>
            {
                subLogger
                .Filter.FilterOnlyTimingLogs()
                .WriteTo.MSSqlServer(connectionString,
                                     tableName: LogConstants.LogTiming,
                                     columnOptions: columnOptions,
                                     restrictedToMinimumLevel: minimumLevel,
                                     autoCreateSqlTable: true);
            });
        }
        private void AddAdditionalColumns(IConfigurationSection config, ColumnOptions columnOptions)
        {
            var newcols =
                config.GetSection("additionalColumns").Get <List <SqlColumn> >()
                ?? config.GetSection("customColumns").Get <List <SqlColumn> >(); // backwards-compatibility

            if (newcols != null)
            {
                foreach (var c in newcols)
                {
                    if (!string.IsNullOrWhiteSpace(c.ColumnName))
                    {
                        if (columnOptions.AdditionalColumns == null)
                        {
                            columnOptions.AdditionalColumns = new Collection <SqlColumn>();
                        }

                        columnOptions.AdditionalColumns.Add(c);
                    }
                }
            }
        }
示例#15
0
        private static LoggerConfiguration WriteToSqlCustom(this LoggerConfiguration logConfig)
        {
            var columnOptions = new ColumnOptions();

            // xml column
            columnOptions.Store.Remove(StandardColumn.Properties);

            // json column
            columnOptions.Store.Add(StandardColumn.LogEvent);
            columnOptions.LogEvent.ExcludeAdditionalProperties = true;

            // special columns for indexing
            columnOptions.AdditionalColumns = new List <SqlColumn>()
            {
                new SqlColumn {
                    ColumnName = "Source", AllowNull = true, DataType = SqlDbType.NVarChar, DataLength = 128
                },
                new SqlColumn {
                    ColumnName = "CorrelationId", AllowNull = true, DataType = SqlDbType.NVarChar, DataLength = 50
                },
                new SqlColumn {
                    ColumnName = "JobName", AllowNull = true, DataType = SqlDbType.NVarChar, DataLength = 50
                },
                new SqlColumn {
                    ColumnName = "JobId", AllowNull = true, DataType = SqlDbType.NVarChar, DataLength = 50
                },
            };

            return(logConfig
                   .WriteTo.MSSqlServer(
                       connectionString: _configuration.GetConnectionString("DefaultConnection"),
                       restrictedToMinimumLevel: LogEventLevel.Information,
                       columnOptions: columnOptions,
                       sinkOptions: new MSSqlServerSinkOptions
            {
                TableName = "Logs",
            }
                       ));
        }
示例#16
0
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
            var logDB = _configuration.GetConnectionString("DefaultConnection");
            var logTable = "TBL_LOG_WORK";
            var options = new ColumnOptions();
            options.Store.Add(StandardColumn.LogEvent);
            options.Store.Remove(StandardColumn.MessageTemplate);
            options.Store.Remove(StandardColumn.Properties);
            options.LogEvent.DataLength = 2048;
            options.PrimaryKey = options.TimeStamp;
            options.TimeStamp.NonClusteredIndex = true;
            Log.Logger = new Serilog.LoggerConfiguration()
                .MinimumLevel.Information()
                //.WriteTo.RollingFile("Log-{Date}.txt", retainedFileCountLimit: 2)
                .WriteTo.MSSqlServer(connectionString: logDB, tableName: logTable, columnOptions: options, restrictedToMinimumLevel: LogEventLevel.Information)
                .CreateLogger();

            // Setting clock provider, using local time
            Clock.Provider = new UtcClockProvider();
            Log.Information("Web Start");
        }
示例#17
0
        internal static SinkDependencies Create(
            string connectionString,
            SinkOptions sinkOptions,
            IFormatProvider formatProvider,
            ColumnOptions columnOptions,
            ITextFormatter logEventFormatter)
        {
            columnOptions = columnOptions ?? new ColumnOptions();
            columnOptions.FinalizeConfigurationForSinkConstructor();

            var sqlConnectionFactory =
                new SqlConnectionFactory(connectionString,
                                         sinkOptions?.UseAzureManagedIdentity ?? default,
                                         new AzureManagedServiceAuthenticator(
                                             sinkOptions?.UseAzureManagedIdentity ?? default,
                                             sinkOptions.AzureServiceTokenProviderResource));
            var logEventDataGenerator =
                new LogEventDataGenerator(columnOptions,
                                          new StandardColumnDataGenerator(columnOptions, formatProvider,
                                                                          new XmlPropertyFormatter(),
                                                                          logEventFormatter),
                                          new PropertiesColumnDataGenerator(columnOptions));

            var sinkDependencies = new SinkDependencies
            {
                SqlTableCreator = new SqlTableCreator(
                    sinkOptions.TableName, sinkOptions.SchemaName, columnOptions,
                    new SqlCreateTableWriter(), sqlConnectionFactory),
                DataTableCreator   = new DataTableCreator(sinkOptions.TableName, columnOptions),
                SqlBulkBatchWriter = new SqlBulkBatchWriter(
                    sinkOptions.TableName, sinkOptions.SchemaName,
                    columnOptions.DisableTriggers, sqlConnectionFactory, logEventDataGenerator),
                SqlLogEventWriter = new SqlLogEventWriter(
                    sinkOptions.TableName, sinkOptions.SchemaName,
                    sqlConnectionFactory, logEventDataGenerator)
            };

            return(sinkDependencies);
        }
示例#18
0
        public static void Main(string[] args)
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var columnOptions    = new ColumnOptions
            {
                AdditionalColumns = new Collection <SqlColumn>
                {
                    new SqlColumn("UserName", SqlDbType.NVarChar)
                }
            };

            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.MSSqlServer(connectionString, sinkOptions: new MSSqlServerSinkOptions {
                TableName = "Logs"
            }
                                              , null, null, LogEventLevel.Information, null, columnOptions: columnOptions, null, null)
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Error)//To capture Information and error only
                         .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }
示例#19
0
        public void TableCreatedWithCustomNamesLegacyInterface()
        {
            // Arrange
            var options       = new ColumnOptions();
            var standardNames = new List <string> {
                "CustomMessage", "CustomMessageTemplate", "CustomLevel", "CustomTimeStamp", "CustomException", "CustomProperties"
            };

            options.Message.ColumnName         = "CustomMessage";
            options.MessageTemplate.ColumnName = "CustomMessageTemplate";
            options.Level.ColumnName           = "CustomLevel";
            options.TimeStamp.ColumnName       = "CustomTimeStamp";
            options.Exception.ColumnName       = "CustomException";
            options.Properties.ColumnName      = "CustomProperties";

            // Act
            using (var sink = new MSSqlServerSink(DatabaseFixture.LogEventsConnectionString, DatabaseFixture.LogTableName, 1, TimeSpan.FromSeconds(1), null, true, options, "dbo", null))
            { }

            // Assert
            VerifyDatabaseColumnsWereCreated(standardNames);
        }
        public static void Main()
        {
            var options = new ColumnOptions();

            options.Store.Add(StandardColumn.LogEvent);
            var customFormatter = new FlatLogEventFormatter();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer(_connectionString,
                                              _tableName,
                                              appConfiguration: null,
                                              restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose,
                                              batchPostingLimit: 50,
                                              period: null,
                                              formatProvider: null,
                                              autoCreateSqlTable: true,
                                              columnOptions: options,
                                              columnOptionsSection: null,
                                              schemaName: _schemaName,
                                              logEventFormatter: customFormatter)
                         .CreateLogger();

            try
            {
                Log.Debug("Getting started");

                Log.Information("Hello {Name} from thread {ThreadId}", Environment.GetEnvironmentVariable("USERNAME"), Thread.CurrentThread.ManagedThreadId);

                Log.Warning("No coins remain at position {@Position}", new { Lat = 25, Long = 134 });

                Fail();
            }
            catch (DivideByZeroException e)
            {
                Log.Error(e, "Division by zero");
            }

            Log.CloseAndFlush();
        }
示例#21
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            var options = new ColumnOptions();

            options.Store.Add(StandardColumn.LogEvent);

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

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer(
                connectionString: _connectionString,
                sinkOptions: new MSSqlServerSinkOptions
            {
                TableName          = _tableName,
                SchemaName         = _schemaName,
                AutoCreateSqlTable = true
            },
                columnOptions: options)
                         .CreateLogger();

            try
            {
                Log.Information("[CUSTOM] Application Started Up at {Now} Thread {Thread}",
                                DateTime.Now, Thread.CurrentThread.ManagedThreadId);
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "The application failed to start correctly!");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static void ConfigureSerilog(this IConfigurationRoot configurationRoot)
        {
            var sinkOptions = new SinkOptions
            {
                TableName          = "Logs",
                AutoCreateSqlTable = true
            };

            var columnOpts = new ColumnOptions();

            columnOpts.Store.Remove(StandardColumn.Properties);
            columnOpts.Store.Remove(StandardColumn.MessageTemplate);
            columnOpts.Store.Remove(StandardColumn.LogEvent);

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer(
                configurationRoot.GetConnectionString("UploaderConnection"),
                sinkOptions,
                columnOptions: columnOpts,
                appConfiguration: configurationRoot
                ).CreateLogger();
        }
示例#23
0
        private static ColumnOptions GetSqlColumnOptions()
        {
            var options = new ColumnOptions();

            options.Store.Remove(StandardColumn.Message);
            options.Store.Remove(StandardColumn.MessageTemplate);
            options.Store.Remove(StandardColumn.Level);
            options.Store.Remove(StandardColumn.Exception);

            options.Store.Remove(StandardColumn.Properties);
            options.Store.Add(StandardColumn.LogEvent);
            options.LogEvent.ExcludeStandardColumns      = true;
            options.LogEvent.ExcludeAdditionalProperties = true;

            options.AdditionalColumns = new Collection <SqlColumn>
            {
                new SqlColumn
                {
                    ColumnName        = "PerfItem", AllowNull = false,
                    DataType          = SqlDbType.NVarChar, DataLength = 100,
                    NonClusteredIndex = true
                },
                new SqlColumn
                {
                    ColumnName = "ElapsedMilliseconds", AllowNull = false,
                    DataType   = SqlDbType.Int
                },
                new SqlColumn
                {
                    ColumnName = "ActionName", AllowNull = false
                },
                new SqlColumn
                {
                    ColumnName = "MachineName", AllowNull = false
                }
            };

            return(options);
        }
        public void Should_insert_additional_columns_on_insert_statement_when_configured()
        {
            var newColumnName     = "XColumns";
            var additionalColumns = new HashSet <string>()
            {
                newColumnName
            };
            var columnOptions = new ColumnOptions
            {
                AdditionalDataColumns = new List <DataColumn>
                {
                    new DataColumn(newColumnName, typeof(string))
                }
            };

            var database         = new OracleDatabaseBatchSink(ConnectionString, TableName, FunctionName, columnOptions, additionalColumns, null);
            var defaultDataTable = database.CreateDataTable();

            var(id, message, messageTemplate, level, timestamp, exception, properties) =
                ("seq", "", "", "Debug", DateTime.MaxValue, "", "<properties></properties>");

            var defaultColumns = (
                from DataColumn dataColumn
                in defaultDataTable.Columns
                select dataColumn.ColumnName).ToList();

            var columns = string.Join(", ", defaultColumns.Select(x => $@"""{x}"""));

            defaultColumns.RemoveAt(0);
            var parameters = string.Join(", ", defaultColumns.Select(x => $":{x}_0"));

            defaultDataTable.Rows.Add(id, message, messageTemplate, level, timestamp, exception, properties);
            var(insert, _) = database.CreateInsertData(defaultDataTable);

            var insertStatementExpected =
                $"INSERT ALL {Environment.NewLine}  INTO {TableName} ({columns}) VALUES (seq, {parameters}){Environment.NewLine}SELECT * FROM dual{Environment.NewLine}";

            insert.Should().BeEquivalentTo(insertStatementExpected);
        }
        public void ColumnstoreIndex()
        {
            // Arrange
            var columnOptions = new ColumnOptions();

            // char MAX not supported prior to SQL2017
            columnOptions.Exception.DataLength       = 512;
            columnOptions.Level.DataLength           = 16;
            columnOptions.Message.DataLength         = 1024;
            columnOptions.MessageTemplate.DataLength = 1536;
            columnOptions.Properties.DataLength      = 2048;
            columnOptions.ClusteredColumnstoreIndex  = true;

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer
                         (
                connectionString: DatabaseFixture.LogEventsConnectionString,
                new SinkOptions
            {
                TableName          = DatabaseFixture.LogTableName,
                AutoCreateSqlTable = true,
                BatchPostingLimit  = 1,
                BatchPeriod        = TimeSpan.FromSeconds(10)
            },
                columnOptions: columnOptions
                         )
                         .CreateLogger();
            Log.CloseAndFlush();

            // Assert
            using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
            {
                conn.Execute($"use {DatabaseFixture.Database}");
                var query   = conn.Query <SysIndex_CCI>("select name from sys.indexes where type = 5");
                var results = query as SysIndex_CCI[] ?? query.ToArray();

                results.Should().Contain(x => x.name == $"CCI_{DatabaseFixture.LogTableName}");
            }
        }
示例#26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // configure Serilog
            var connectionString = Configuration.GetConnectionString("dbConnection");
            var logTable         = "Logs";

            var columnOptions = new ColumnOptions()
            {
                AdditionalDataColumns = new List <DataColumn> {
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "ServerName"
                    },
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "ClientName"
                    }
                }
            };

            var loggerConfig = new LoggerConfiguration()
                               .WriteTo.MSSqlServer(connectionString, logTable, columnOptions: columnOptions)
                               .Enrich.With <ColumnsEnricher>();

            var logger = loggerConfig.CreateLogger();

            loggerFactory.AddSerilog(logger);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
示例#27
0
        public static int Main(string[] args)
        {
            //Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

            ColumnOptions columnOptions = new ColumnOptions();

            // Don't include the Properties XML column.
            columnOptions.Store.Remove(StandardColumn.Properties);
            // Do include the log event data as JSON.
            columnOptions.Store.Add(StandardColumn.LogEvent);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.MSSqlServer(Configuration.GetConnectionString("IdentityServiceConnection"), Configuration["Serilog:TableName"], columnOptions: columnOptions, schemaName: "IdentityService")
                         .WriteTo.Console()
                         .WriteTo.ApplicationInsightsEvents(Configuration["ApplicationInsights:InstrumentationKey"])
                         .CreateLogger();

            try
            {
                Log.Information("Starting host");

                BuildWebHost(args).Run();

                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
示例#28
0
        /// <summary>
        /// Create and initialize a Serilog logger
        /// </summary>
        /// <returns>Serilog <see cref="Logger"/></returns>
        public static Logger GetLogger()
        {
            var databaseConnectionString = ConfigurationManager.ConnectionStrings["DCCDatabase"].ConnectionString;
            var rollingFileLocation      = ConfigurationManager.AppSettings["LoggingFileLocation"];

            var columnOptions = new ColumnOptions
            {
                Store = new Collection <StandardColumn>
                {
                    StandardColumn.TimeStamp,   // Date
                    StandardColumn.Level,
                    StandardColumn.Message,
                    StandardColumn.Exception,
                },
                AdditionalDataColumns = new Collection <DataColumn>
                {
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "Table", AllowDBNull = true
                    },
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "MachineName", AllowDBNull = true
                    },
                    new DataColumn {
                        DataType = typeof(string), ColumnName = "SourceContext", AllowDBNull = true
                    }
                },
                Id        = { ColumnName = "ID" },
                TimeStamp = { ColumnName = "Date" }
            };

            return(new LoggerConfiguration()
                   .Enrich.FromLogContext()
                   .Enrich.WithMachineName()
                   .WriteTo.MSSqlServer(databaseConnectionString, "Log", LogEventLevel.Information, columnOptions: columnOptions)
                   .WriteTo.Console()
                   .WriteTo.RollingFile(rollingFileLocation)
                   .CreateLogger());
        }
示例#29
0
        public void Reinitialize(List <FilterOption> filters, List <ColumnOption> columns, ColumnOptionsMode columnOptionsMode, List <OrderOption> orders, Pagination pagination)
        {
            try
            {
                avoidPaginationChange = true;

                ColumnOptions.Clear();
                ColumnOptions.AddRange(columns);
                ColumnOption.SetColumnTokens(ColumnOptions, Description);
                ColumnOptionsMode = columnOptionsMode;
                GenerateListViewColumns();

                if (!filters.SequenceEqual(FilterOptions))
                {
                    if (SimpleFilterBuilder != null)
                    {
                        SimpleFilterBuilder = null;
                    }

                    FilterOptions.Clear();
                    FilterOption.SetFilterTokens(filters, Description);
                    FilterOptions.AddRange(filters);
                }

                OrderOptions.Clear();
                OrderOptions.AddRange(orders);
                OrderOption.SetOrderTokens(OrderOptions, Description);
                SortGridViewColumnHeader.SetColumnAdorners(gvResults, OrderOptions);

                UpdateMultiplyMessage(true);

                Pagination = pagination;
            }
            finally
            {
                avoidPaginationChange = false;
            }
        }
示例#30
0
        public void AuditEventToCustomStandardColumnsSinkOptionsInterface()
        {
            // Arrange
            var options = new ColumnOptions();

            options.Message.ColumnName         = "CustomMessage";
            options.MessageTemplate.ColumnName = "CustomMessageTemplate";
            options.Level.ColumnName           = "CustomLevel";
            options.TimeStamp.ColumnName       = "CustomTimeStamp";
            options.Exception.ColumnName       = "CustomException";
            options.Properties.ColumnName      = "CustomProperties";
            options.Id.ColumnName = "CustomId";

            var loggerConfiguration = new LoggerConfiguration();

            Log.Logger = loggerConfiguration.AuditTo.MSSqlServer(
                connectionString: DatabaseFixture.LogEventsConnectionString,
                sinkOptions: new SinkOptions
            {
                TableName          = DatabaseFixture.LogTableName,
                AutoCreateSqlTable = true
            },
                columnOptions: options)
                         .CreateLogger();

            // Act
            const string loggingInformationMessage = "Logging Information message";

            using (var file = File.CreateText("CustomColumnsAuditEvent.Self.log"))
            {
                Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));
                Log.Information(loggingInformationMessage);
                Log.CloseAndFlush();
            }

            // Assert
            VerifyCustomLogMessageWasWritten(loggingInformationMessage);
        }
示例#31
0
        static void Main(string[] args)
        {
            string logConnString = "Data Source=zeus;Initial Catalog=pruebaSerilog;Integrated Security=True";
            var    columnOptions = new ColumnOptions();

            columnOptions.AdditionalDataColumns = new Collection <DataColumn>
            {
                new DataColumn {
                    DataType = typeof(string), ColumnName = "Category"
                },
                new DataColumn {
                    DataType = typeof(string), ColumnName = "MachineName"
                },
                new DataColumn {
                    DataType = typeof(string), ColumnName = "AppDomainName"
                },
                new DataColumn {
                    DataType = typeof(string), ColumnName = "ProcessName"
                },
            };

            columnOptions.Properties.ExcludeAdditionalProperties = true;

            columnOptions.Store.Remove(StandardColumn.MessageTemplate);

            var log = new LoggerConfiguration()
                      .Enrich.With(new CommonLogEnricher())
                      .WriteTo.Console()
                      .WriteTo.MSSqlServer(logConnString, tableName: "Logs", restrictedToMinimumLevel: LogEventLevel.Error, columnOptions: columnOptions)
                      .CreateLogger();

            PruebaTraceService(log);
            //Pruebasbasicas(log);

            //log.Information("Retrieved {Count} records", new Coso {  Count = 1});

            Console.ReadLine();
        }
示例#32
0
 public ColumnDescription(ColumnReference column, ColumnOptions options)
 {
     this.column = column;
     this.options = options;
 }
 protected AbstractColumnCommandWithOptions(int num, XElement inner)
     : base(num, inner)
 {
     this.options = XMLParser.ParseColumnOptions(inner);
 }