Skip to content

Commit

Permalink
Fixed a string truncate bug.
Browse files Browse the repository at this point in the history
  • Loading branch information
Whinarn committed Dec 21, 2023
1 parent 215e91b commit 767b8d6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ public static string TruncateOutput(this string value, int dataLength) =>
public static string Truncate(this string value, int maxLength, string suffix)
{
if (value == null) return null;
else if (value.Length <= maxLength) return value;

var suffixLength = suffix?.Length ?? 0;
if (maxLength <= suffixLength) return string.Empty;

var correctedMaxLength = maxLength - suffixLength;
return value.Length <= maxLength ? value : Invariant($"{value.Substring(0, correctedMaxLength)}{suffix}");
return Invariant($"{value.Substring(0, correctedMaxLength)}{suffix}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,28 @@ public void GetAdditionalColumnNameAndValueReturnsTruncatedForCharacterTypesWith
Assert.Equal(columnName, result.Key);
Assert.Equal("Additio...", result.Value);
}

[Fact]
[Trait("Bugfix", "#505")]
public void GetAdditionalColumnNameAndValueReturnsFullStringWithOneDataLength()
{
// Arrange
const string columnName = "AdditionalProperty1";
const string propertyValue = "A";
var additionalColumn = new SqlColumn(columnName, SqlDbType.NVarChar);
additionalColumn.DataLength = 1;
var properties = new Dictionary<string, LogEventPropertyValue>();
_columnSimplePropertyValueResolver.Setup(r => r.GetPropertyValueForColumn(
It.IsAny<SqlColumn>(), It.IsAny<IReadOnlyDictionary<string, LogEventPropertyValue>>()))
.Returns(new KeyValuePair<string, LogEventPropertyValue>(columnName, new ScalarValue(propertyValue)));

// Act
var result = _sut.GetAdditionalColumnNameAndValue(additionalColumn, properties);

// Assert
_columnSimplePropertyValueResolver.Verify(r => r.GetPropertyValueForColumn(additionalColumn, properties), Times.Once);
Assert.Equal(columnName, result.Key);
Assert.Equal(propertyValue, result.Value);
}
}
}

0 comments on commit 767b8d6

Please sign in to comment.