S2629 in C# raises an issue “Don’t use string interpolation in logging message templates” with the following code:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[...]
catch (Exception ex)
{
log.Error($"Error while loading file '{filePath}'!", ex); // S2629
}
Using
log.ErrorFormat("Error while loading file '{0}'!", filePath, ex);
would not be a feasible solution in this case because it is semantically different in its handing of the Exception object.
The API documentation of ErrorFormat
explicitly states that the regular Error
method should be used if you need to log an Exception:
The message is formatted using the String.Format method. See String.Format(string, object[.]) for details of the syntax of the format string and the behavior of the formatting.
This method does not take an System.Exception object to include in the log event.
To pass an System.Exception use one of the Error(object) methods instead.
Therefore the Sonar rule should not flag this as an issue if you use an interpolated string in the logging as long as you also pass the Exception object as additional parameter.