#4 PatternLayout

open
nobody
None
5
2009-07-25
2009-07-25
Martin Heinrich
No

When using the L4PatternLayout the minimum specifiers for fields are ignored. I am using the pattern @"%8r %-5p %M - %m%n". When calling the macro log4CInfo from the class method initializeLogging of the class UTLogging I would expect the following output

4 INFO +[UTLogging initializeLogging] - Logging initialized

Instead the output is

4 INFO +[UTLogging initializeLogging] - Logging initialized

As far as I can tell the format string used by L4PatternLayout convertTokenString is correct (@"%-*@"). I did a quick test and found that using a minimum specifier with appendFormat seems to not work at all:

int i = 5;
NSString *a = @"X";
NSMutableString *buffer = [NSMutableString stringWithCapacity: 50];
[buffer appendFormat:@"'%5@', ", a];
[buffer appendFormat:@"'%*@', ", i, a];
[buffer appendFormat:@"'%-5@', ", a];
[buffer appendFormat:@"'%-*@'", i, a];
NSLog(buffer);

produces the output

2009-07-25 15:14:31.454 MyApp[25146:10b] 'X', 'X', 'X', 'X'

Discussion

  • To resolve the problem I replaced the list of if..else in L4PatternLayout statements with the following code:

    // Minimum length
    if (minLength > 0 && [tempString length] < minLength)
    {
    int length = minLength - [tempString length];
    NSMutableString *spaces = [NSMutableString stringWithCapacity:length];
    for (int i=0; i < length; i++)
    {
    [spaces appendString:@" "];
    }
    if (leftJustify)
    {
    tempString = [tempString stringByAppendingString:spaces];
    } else {
    tempString = [spaces stringByAppendingString:tempString];
    }
    }
    // Maximum length
    if (maxLength > 0 && [tempString length] > maxLength)
    {
    tempString = [tempString substringFromIndex:[tempString length] - maxLength];
    }
    [finalResultString appendString:tempString];