If I try to use Encryption using NServiceBus.Encryption.Message nuget package with the Nlog.Extensions.Logging and the Microsoft.Extensions.Logging, then I get the error " Invalid format string. Expected 3 format parameters, but failed to lookup parameter index 2." at NLog.Extensions.Logging.
The inner exception is “Index was outside the bounds of the array.” at the Microsoft.Extensions.Logging.Abstractions.
Example code:
// Set NSB to use NLog with microsoft extension
Microsoft.Extensions.Logging.ILoggerFactory extensionsLoggerFactory = new NLogLoggerFactory();
ILoggerFactory nservicebusLoggerFactory = new ExtensionsLoggerFactory(loggerFactory: extensionsLoggerFactory);
LogManager.UseFactory(loggerFactory: nservicebusLoggerFactory);
//encryption
var encryptionService = new RijndaelEncryptionService(
encryptionKeyIdentifier: "2015-10",
key: Convert.FromBase64String("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"));
I found that Microsoft Extension Logging has no support for string-formatted message but only structured message. So {2} {1} and {0} will be parsed as names (from left to right).
Also I noticed the class RijndaelEncryptionService in the namespace NServiceBus.Encryption.MessageProperty uses the log format like the above which might caused this issue.
please refer the code in the class RijndaelEncryptionService which follows the above logging method
static bool IsValidKey(byte[] key)
{
using (var rijndael = new RijndaelManaged())
{
var bitLength = key.Length*8;
var maxValidKeyBitLength = rijndael.LegalKeySizes.Max(keyLength => keyLength.MaxSize);
if (bitLength < maxValidKeyBitLength)
{
Log.WarnFormat("Encryption key is {0} bits which is less than the maximum allowed {1} bits. Consider using a {1}-bit encryption key to obtain the maximum cipher strength", bitLength, maxValidKeyBitLength);
}
return rijndael.ValidKeySize(bitLength);
}
}
Log.WarnFormat("Encryption key is {0} bits which is less than the maximum allowed {1} bits. Consider using a {1}-bit encryption key to obtain the maximum cipher strength", bitLength, maxValidKeyBitLength);
to
Log.WarnFormat($"Encryption key is {bitLength} bits which is less than the maximum allowed {maxValidKeyBitLength} bits. Consider using a {maxValidKeyBitLength}-bit encryption key to obtain the maximum cipher strength");
works for me. Expecting update of nuget package NServiceBus.Encryption.MessageProperty with this bug fix.
I verified it and indeed Microsoft.Extensions.Logging requires the same amount of args as formatting parameters. So
log.WarnFormat("{0} {0}", "foo", "bar");
works and prints
foo foo
but
log.WarnFormat("{0} {0}", "foo");
throws an exception
System.FormatException: Invalid format string. Expected 2 format parameters, but failed to lookup parameter index 1
---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Microsoft.Extensions.Logging.LogValuesFormatter.GetValue(Object[] values, Int32 index)
at Microsoft.Extensions.Logging.FormattedLogValues.get_Item(Int32 index)