No good solution for avoiding S2629 when trying to log exception and additional args with log4net

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.

Hey there,

I can confirm that this behavior is erroneous.
I added a ticket and a repro to our backlog, where it will be taken care of during some upcoming hardening.

Feel free to track the github issue and/or add any more comments if you want.
Thanks for the suggestion!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.