Jahmic Jahmic - 1 month ago 24
C# Question

log4net (common.logging) erroneous exception

I have the following log4net statement in a c# application:

log.Info(CultureInfo.InvariantCulture, m => m(notice));


with the string contents of:

notice = "Checking: 645: Bp $B!!:{4V7r;K Bp $B$D$^$M$5$S (B <xxx@xxxxxx. Co. Jp> (B <xxxxx@xxxxxxx.Com>)"


causing this exception:


[Common.Logging.Factory.AbstractLogger+FormatMessageCallbackFormattedMessage]System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at Common.Logging.Factory.AbstractLogger.FormatMessageCallbackFormattedMessage.FormatMessage(String format, Object[] args)


If you notice in the string (which, in this case, is a totally piece of garbage) there is a single bracket "{". I'm fairly certain that this is causing the exception. What can I do to avoid this? Escape the string somehow?

It's a fairly harmless exception, except that it shows up in the log file and is distracting.

Answer

It ends up that the Common.Logging log function uses the string.Format functions regardless of whether they are needed or not. So, as @HansKesting mentioned in comments, escaping any unintended brackets (braces) will be needed. So, when logging data that I suspect my have this problem, I changed the code to:

notice = notice.Replace("{", "{{");
log.Info(CultureInfo.InvariantCulture, m => m(notice));

Hopes this helps others.