%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; }