Skip to content

Commit 907cd0a

Browse files
committed
* Adapted WorkerServiceDemo sample app to use custom property names.
* Added integration tests for M.E.C. config extensions regarding custom propery names. * Added hint to readme that custom property is only used for custom columns.
1 parent 0cf3ff0 commit 907cd0a

File tree

9 files changed

+86
-31
lines changed

9 files changed

+86
-31
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ Any valid SQL column name can be used. Standard Columns have default names assig
332332

333333
### PropertyName
334334

335-
The optional name of a Serilog property to use as the value for the SqlColumn. If not provided, the property used is the one that has the same name as the specified ColumnName.
335+
The optional name of a Serilog property to use as the value for a custom column. If not provided, the property used is the one that has the same name as the specified ColumnName. It applies only to custom columns defined in `AdditionalColumns` and is ignored for standard columns.
336336

337337
### DataType
338338

sample/WorkerServiceDemo/Worker.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
2121

2222
while (!stoppingToken.IsCancellationRequested)
2323
{
24-
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
24+
_logger.LogInformation("Worker running at: {time}. CustomProperty1: {CustomProperty1}",
25+
DateTimeOffset.Now, "Value");
2526
await Task.Delay(1000, stoppingToken);
2627
}
2728

sample/WorkerServiceDemo/appsettings.json

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"tableName": "LogEvents",
1919
"autoCreateSqlTable": true,
2020
"useAzureManagedIdentity": false,
21-
"azureServiceTokenProviderResource": "TestAzureServiceTokenProviderResource"
21+
"azureServiceTokenProviderResource": "https://database.windpws.net/"
2222
},
2323
"restrictedToMinimumLevel": "Information",
2424
"columnOptionsSection": {
@@ -27,7 +27,14 @@
2727
"timeStamp": {
2828
"columnName": "Timestamp",
2929
"convertToUtc": false
30-
}
30+
},
31+
"additionalColumns": [
32+
{
33+
"columnName": "AdditionalColumn1",
34+
"propertyName": "CustomProperty1",
35+
"dataType": "12"
36+
}
37+
]
3138
},
3239
"logEventFormatter": "WorkerServiceDemo.CustomLogEventFormatter::Formatter, WorkerServiceDemo"
3340
}
@@ -38,21 +45,28 @@
3845
"Name": "MSSqlServer",
3946
"Args": {
4047
"connectionString": "Server=localhost;Database=LogTest;Integrated Security=SSPI;",
41-
"tableName": "LogEventsAudit",
48+
"restrictedToMinimumLevel": "Information",
49+
"logEventFormatter": "WorkerServiceDemo.CustomLogEventFormatter::Formatter, WorkerServiceDemo",
50+
"sinkOptionsSection": {
51+
"tableName": "LogEventsAudit",
52+
"autoCreateSqlTable": true,
53+
"useAzureManagedIdentity": false,
54+
"azureServiceTokenProviderResource": "https://database.windpws.net/"
55+
},
4256
"columnOptionsSection": {
4357
"addStandardColumns": [ "LogEvent" ],
4458
"removeStandardColumns": [ "MessageTemplate", "Properties" ],
4559
"timeStamp": {
4660
"columnName": "Timestamp",
4761
"convertToUtc": false
48-
}
49-
},
50-
"autoCreateSqlTable": true,
51-
"restrictedToMinimumLevel": "Information",
52-
"logEventFormatter": "WorkerServiceDemo.CustomLogEventFormatter::Formatter, WorkerServiceDemo",
53-
"sinkOptionsSection": {
54-
"useAzureManagedIdentity": false,
55-
"azureServiceTokenProviderResource": "TestAuditAzureServiceTokenProviderResource"
62+
},
63+
"additionalColumns": [
64+
{
65+
"columnName": "AdditionalColumn1",
66+
"propertyName": "CustomProperty1",
67+
"dataType": "12"
68+
}
69+
]
5670
}
5771
}
5872
}

src/Serilog.Sinks.MSSqlServer/Configuration/Implementations/Microsoft.Extensions.Configuration/MicrosoftExtensionsColumnOptionsProvider.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ private static void SetCommonColumnOptions(IConfigurationSection section, SqlCol
2929
{
3030
// Standard Columns are subclasses of the SqlColumn class
3131
SetProperty.IfNotNullOrEmpty<string>(section["columnName"], (val) => target.ColumnName = val);
32-
SetProperty.IfNotNullOrEmpty<string>(section["propertyName"], (val) => target.PropertyName = val);
3332
SetProperty.IfNotNull<string>(section["dataType"], (val) => target.SetDataTypeFromConfigString(val));
3433
SetProperty.IfNotNull<bool>(section["allowNull"], (val) => target.AllowNull = val);
3534
SetProperty.IfNotNull<int>(section["dataLength"], (val) => target.DataLength = val);

test/Serilog.Sinks.MSSqlServer.Tests/App.config

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
<configSections>
44
<section name="CustomStandardColumnNames" type="Serilog.Configuration.MSSqlServerConfigurationSection, Serilog.Sinks.MSSqlServer"/>
55
<section name="CustomizedColumnList" type="Serilog.Configuration.MSSqlServerConfigurationSection, Serilog.Sinks.MSSqlServer"/>
6+
<section name="AdditionalColumnCustomPropertyList" type="Serilog.Configuration.MSSqlServerConfigurationSection, Serilog.Sinks.MSSqlServer"/>
67
<section name="SinkOptionsConfig" type="Serilog.Configuration.MSSqlServerConfigurationSection, Serilog.Sinks.MSSqlServer"/>
78
</configSections>
89
<startup>
@@ -31,6 +32,12 @@
3132
</Columns>
3233
</CustomizedColumnList>
3334

35+
<AdditionalColumnCustomPropertyList>
36+
<Columns>
37+
<add ColumnName="AdditionalColumn1" PropertyName="AdditionalProperty1" DataType="8" />
38+
</Columns>
39+
</AdditionalColumnCustomPropertyList>
40+
3441
<SinkOptionsConfig>
3542
<TableName Value="LogEvents" />
3643
<AutoCreateSqlTable Value="true" />

test/Serilog.Sinks.MSSqlServer.Tests/Configuration/Extensions/Hybrid/ConfigurationExtensionsTests.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ public class ConfigurationExtensionsTests : DatabaseTestsBase
1313
private const string _connectionStringName = "NamedConnection";
1414
private const string _columnOptionsSection = "CustomColumnNames";
1515
private const string _sinkOptionsSection = "SinkOptions";
16+
private const string _additionalColumn1Name = "AdditionalColumn1Name";
17+
private const string _additionalColumn1PropertyName = "AdditionalColumn1PropertyName";
1618

1719
public ConfigurationExtensionsTests(ITestOutputHelper output) : base(output)
1820
{
@@ -61,8 +63,12 @@ public void ConnectionStringByNameFromConfigSinkOptionsInterface()
6163
public void ColumnOptionsFromConfigSectionLegacyInterface()
6264
{
6365
// Arrange
64-
var standardNames = new List<string> { "CustomMessage", "CustomMessageTemplate", "CustomLevel", "CustomTimeStamp", "CustomException", "CustomProperties" };
66+
var standardNames = new List<string> { "CustomMessage", "CustomMessageTemplate", "CustomLevel", "CustomTimeStamp",
67+
"CustomException", "CustomProperties", _additionalColumn1Name };
6568
var columnOptionsSection = TestConfiguration().GetSection(_columnOptionsSection);
69+
var messageTemplate = $"Hello {{{_additionalColumn1PropertyName}}}!";
70+
var propertyValue = 2;
71+
var expectedMessage = $"Hello {propertyValue}!";
6672

6773
// Act
6874
var loggerConfiguration = new LoggerConfiguration();
@@ -72,18 +78,25 @@ public void ColumnOptionsFromConfigSectionLegacyInterface()
7278
autoCreateSqlTable: true,
7379
columnOptionsSection: columnOptionsSection)
7480
.CreateLogger();
81+
Log.Information(messageTemplate, propertyValue);
7582
Log.CloseAndFlush();
7683

7784
// Assert
7885
VerifyDatabaseColumnsWereCreated(standardNames);
86+
VerifyLogMessageWasWritten(expectedMessage, "CustomMessage");
87+
VerifyIntegerColumnWritten(_additionalColumn1Name, propertyValue);
7988
}
8089

8190
[Fact]
8291
public void ColumnOptionsFromConfigSectionSinkOptionsInterface()
8392
{
8493
// Arrange
85-
var standardNames = new List<string> { "CustomMessage", "CustomMessageTemplate", "CustomLevel", "CustomTimeStamp", "CustomException", "CustomProperties" };
94+
var standardNames = new List<string> { "CustomMessage", "CustomMessageTemplate", "CustomLevel", "CustomTimeStamp",
95+
"CustomException", "CustomProperties", _additionalColumn1Name };
8696
var columnOptionsSection = TestConfiguration().GetSection(_columnOptionsSection);
97+
var messageTemplate = $"Hello {{{_additionalColumn1PropertyName}}}!";
98+
var propertyValue = 2;
99+
var expectedMessage = $"Hello {propertyValue}!";
87100

88101
// Act
89102
var loggerConfiguration = new LoggerConfiguration();
@@ -96,10 +109,13 @@ public void ColumnOptionsFromConfigSectionSinkOptionsInterface()
96109
},
97110
columnOptionsSection: columnOptionsSection)
98111
.CreateLogger();
112+
Log.Information(messageTemplate, propertyValue);
99113
Log.CloseAndFlush();
100114

101115
// Assert
102116
VerifyDatabaseColumnsWereCreated(standardNames);
117+
VerifyLogMessageWasWritten(expectedMessage, "CustomMessage");
118+
VerifyIntegerColumnWritten(_additionalColumn1Name, propertyValue);
103119
}
104120

105121
[Fact]
@@ -135,6 +151,9 @@ private IConfiguration TestConfiguration() =>
135151
{ $"{_columnOptionsSection}:timeStamp:columnName", "CustomTimeStamp" },
136152
{ $"{_columnOptionsSection}:exception:columnName", "CustomException" },
137153
{ $"{_columnOptionsSection}:properties:columnName", "CustomProperties" },
154+
{ $"{_columnOptionsSection}:additionalColumns:0:columnName", _additionalColumn1Name },
155+
{ $"{_columnOptionsSection}:additionalColumns:0:propertyName", _additionalColumn1PropertyName },
156+
{ $"{_columnOptionsSection}:additionalColumns:0:dataType", "8" },
138157

139158
{ $"{_sinkOptionsSection}:tableName", DatabaseFixture.LogTableName },
140159
{ $"{_sinkOptionsSection}:autoCreateSqlTable", "true" },

test/Serilog.Sinks.MSSqlServer.Tests/Configuration/Extensions/System.Configuration/ConfigurationExtensionsTests.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,5 +109,33 @@ public void CustomizedColumnListFromConfig()
109109
// Assert
110110
VerifyDatabaseColumnsWereCreated(new List<string> { "LogEvent", "CustomColumn" });
111111
}
112+
113+
[Fact]
114+
public void AdditionalColumnWithCustomPropertyNameFromConfig()
115+
{
116+
// Arrange
117+
const string additionalColumnName = "AdditionalColumn1";
118+
const string additionalPropertyName = "AdditionalProperty1";
119+
var messageTemplate = $"Hello {{{additionalPropertyName}}}!";
120+
var propertyValue = 2;
121+
var expectedMessage = $"Hello {propertyValue}!";
122+
123+
// Act
124+
var loggerConfiguration = new LoggerConfiguration();
125+
Log.Logger = loggerConfiguration.WriteTo.MSSqlServerInternal(
126+
configSectionName: "AdditionalColumnCustomPropertyList",
127+
connectionString: DatabaseFixture.LogEventsConnectionString,
128+
sinkOptions: new SinkOptions { TableName = DatabaseFixture.LogTableName, AutoCreateSqlTable = true },
129+
applySystemConfiguration: new ApplySystemConfiguration(),
130+
sinkFactory: new MSSqlServerSinkFactory())
131+
.CreateLogger();
132+
Log.Information(messageTemplate, propertyValue);
133+
Log.CloseAndFlush();
134+
135+
// Assert
136+
VerifyDatabaseColumnsWereCreated(new List<string> { additionalColumnName });
137+
VerifyIntegerColumnWritten(additionalColumnName, propertyValue);
138+
VerifyLogMessageWasWritten(expectedMessage);
139+
}
112140
}
113141
}

test/Serilog.Sinks.MSSqlServer.Tests/Configuration/Implementations/Microsoft.Extensions.Configuration/MicrosoftExtensionsColumnOptionsProviderTests.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -659,12 +659,6 @@ public void ConfigureColumnOptionsThrowsWhenSettingPrimaryKeyColumnNameToUndefin
659659
Assert.Throws<ArgumentException>(() => sut.ConfigureColumnOptions(columnOptions, _configurationSectionMock.Object));
660660
}
661661

662-
[Fact]
663-
public void ConfigureColumnOptionsSetsPropertyNameForAdditionalColumn()
664-
{
665-
// TODO Implement test
666-
}
667-
668662
private static void AssertColumnSqlOptions(string expectedColumnName, SqlDbType expectedDataType, bool expectedAllowNull, bool expectedNonClusteredIndex, SqlColumn actualColumn)
669663
{
670664
Assert.Equal(expectedColumnName, actualColumn.ColumnName);

test/Serilog.Sinks.MSSqlServer.Tests/TestUtils/DatabaseTestsBase.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -94,16 +94,9 @@ protected static void VerifyIdColumnWasCreatedAndHasIdentity(string idColumnName
9494
}
9595
}
9696

97-
protected static void VerifyLogMessageWasWritten(string expectedMessage)
97+
protected static void VerifyLogMessageWasWritten(string expectedMessage, string messageColumnName = "Message")
9898
{
99-
//using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
100-
//{
101-
// var logEvents = conn.Query<DefaultStandardLogColumns>($"SELECT * FROM {DatabaseFixture.LogTableName}");
102-
103-
// logEvents.Should().Contain(e => e.Message.Contains(message));
104-
//}
105-
106-
VerifyStringColumnWritten("Message", expectedMessage);
99+
VerifyStringColumnWritten(messageColumnName, expectedMessage);
107100
}
108101

109102
protected static void VerifyStringColumnWritten(string columnName, string expectedValue)

0 commit comments

Comments
 (0)