This rule ensures the parameters for Microsoft.Extensions.Logging's logger are of the expected types. You can configure the expected types using a configuration file.
To configure the rule, you need to create a file named LoggerParameterTypes.txt
or LoggerParameterTypes.*.txt
.
- Each line is of the form
PropertyName;ExpectedType1;ExpectedType2;ExpectedType3;...
- A type is represented by its CLR metadata name or XML Comment ID reference
- Lines starting with
#
are comments
# This is a comment
Name;System.String
Count;System.Int32;System.Int64
Length;System.Int32;System.Nullable{System.Int32}
AccountId;System.Nullable{System.Guid}
# Deny parameter
InvalidParameter;
Then, you need to add the file to the AdditionalFiles
collection in the csproj
file:
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<AdditionalFiles Include="$(MSBuildThisFileDirectory)\LoggerParameterTypes.txt" />
</ItemGroup>
</Project>
You can also configure the allowed types by using an assembly attribute. This attributes are applied only for the current assemblies. The rule does not consider attributes defined in referenced assemblies.
// Requires the Meziantou.Analyzer.Annotations package
[assembly: Meziantou.Analyzer.Annotations.StructuredLogField("Count", typeof(int), typeof(long))]
Then, the analyzer reports log parameters of the wrong type:
using Microsoft.Extensions.Logging;
ILogger logger = ...;
logger.LogInformation("{Name}", 123); // non-compliant as the configuration file indicates Name should be of type string
logger.LogInformation("{Name}", "dummy"); // ok