似乎仅使用配置是不可能的。下一个更简单的解决方案似乎是自定义 PatternLayout,然后可以在 log4j.ini 中使用字符“b”:
log4j.appender.filelog.layout= your.full.namespace.BPatternLayout log4j.appender.filelog.layout.ConversionPattern=[%d{ISO8601}] %-5p %-30b %m%n
希望它也对其他人有所帮助。
BPatternLayout.java:
import org.apache.log4j.PatternLayout;
import org.apache.log4j.helpers.PatternParser;
public class BPatternLayout extends PatternLayout
{
@Override
protected PatternParser createPatternParser(String pattern)
{
return new BPatternParser(pattern);
}
}
BPatternParser.java:
import org.apache.log4j.helpers.FormattingInfo;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
public class BPatternParser extends PatternParser
{
public BPatternParser(String pattern)
{
super(pattern);
}
@Override
protected void finalizeConverter(char c)
{
switch (c)
{
case 'b':
currentLiteral.setLength(0);
addConverter(new BPatternConverter(formattingInfo));
break;
default:
super.finalizeConverter(c);
}
}
private class BPatternConverter extends PatternConverter
{
BPatternConverter(FormattingInfo formattingInfo)
{
super(formattingInfo);
}
@Override
protected String convert(LoggingEvent evt)
{
LocationInfo locationInfo = evt.getLocationInformation();
return getPartialClassName(locationInfo, 1) + ":" + locationInfo.getMethodName();
}
/**
* Code from org.apache.log4j.helpers.PatternParser.NamedPatternConverter
*/
private String getPartialClassName(LocationInfo loc, int precision)
{
String n = loc.getClassName();
if (precision <= 0) {
return n;
}
int len = n.length();
// We substract 1 from 'len' when assigning to 'end' to avoid out of
// bounds exception in return r.substring(end+1, len). This can happen if
// precision is 1 and the category name ends with a dot.
int end = len - 1;
for (int i = precision; i > 0; i--)
{
end = n.lastIndexOf('.', end - 1);
if (end == -1)
return n;
}
return n.substring(end + 1, len);
}
}
}