%c{参数}或%logger{参数}
输出logger的名称,即语句private static final Logger logger = LogManager.getLogger(App.class.getName())中App.class.getName()的值。也可以使用其他字符串。
pattern表达式 |
logger名称 |
结果 |
%c{1} |
org.apache.com.te.Foo |
Foo |
%c{2} |
org.apache.com.te.Foo |
te.Foo |
%c{1.} |
org.apache.com.te.Foo |
o.a.c.t.Foo |
%c{1.1.!} |
org.apache.com.te.Foo |
o.a.!.!.Foo |
%c{.} |
org.apache.com.te.Foo |
….Foo |
1:如果{}内是正整数 N 那么表示,将类名使用.分割,保留右边数N个。0是正整数 至少会保留类名
2:如果{}内是负整数 N 那么表示,将类名使用.分割,删除左边数N个。
3:使用.分割N个区域,同时将类目也使用.分割M个区域 N[0]处理M[0] 依次类推 如果N短 那么 N[最后一个] 处理 M[所有没有对应的]
对于每一个N的区域,都需要初始化两个变量,charCount也就是对应M区域内保留的字符串,ellipsis表示分隔符,注意'\0'表示删除
逻辑如下
相关源码参考
/** * Gets an abbreviator. * <p> * For example, "%logger{2}" will output only 2 elements of the logger name, "%logger{1.}" will output only the * first character of the non-final elements in the name, "%logger(1~.2~} will output the first character of the * first element, two characters of the second and subsequent elements and will use a tilde to indicate abbreviated * characters. * </p> * * @param pattern * abbreviation pattern. * @return abbreviator, will not be null. */ public static NameAbbreviator getAbbreviator(final String pattern) { if (pattern.length() > 0) { // if pattern is just spaces and numbers then // use MaxElementAbbreviator final String trimmed = pattern.trim(); if (trimmed.isEmpty()) { return DEFAULT; } boolean isNegativeNumber; final String number; // check if number is a negative number if (trimmed.length() > 1 && trimmed.charAt(0) == '-') { isNegativeNumber = true; number = trimmed.substring(1); } else { isNegativeNumber = false; number = trimmed; } int i = 0; while (i < number.length() && number.charAt(i) >= '0' && number.charAt(i) <= '9') { i++; } // // if all blanks and digits // if (i == number.length()) { return new MaxElementAbbreviator(Integer.parseInt(number), isNegativeNumber? MaxElementAbbreviator.Strategy.DROP : MaxElementAbbreviator.Strategy.RETAIN); } final ArrayList<PatternAbbreviatorFragment> fragments = new ArrayList<>(5); char ellipsis; int charCount; int pos = 0; while (pos < trimmed.length() && pos >= 0) { int ellipsisPos = pos; if (trimmed.charAt(pos) == '*') { charCount = Integer.MAX_VALUE; ellipsisPos++; } else if (trimmed.charAt(pos) >= '0' && trimmed.charAt(pos) <= '9') { charCount = trimmed.charAt(pos) - '0'; ellipsisPos++; } else { charCount = 0; } ellipsis = '\0'; if (ellipsisPos < trimmed.length()) { ellipsis = trimmed.charAt(ellipsisPos); if (ellipsis == '.') { ellipsis = '\0'; } } fragments.add(new PatternAbbreviatorFragment(charCount, ellipsis)); pos = trimmed.indexOf('.', pos); if (pos == -1) { break; } pos++; } return new PatternAbbreviator(fragments); } // // no matching abbreviation, return defaultAbbreviator // return DEFAULT; }