log4j: abbreviate/shorten package names

2019-03-08 05:35发布

How would i abbreviate/shorten package names in log generated using log4j. i.e. instead of com.longpackage.anotherpackage.lastpackage.MyClass i want c.l.a.l.MyClass. I have seen this in Artifactory logs, but can't figure how to achieve this using log4j.

2条回答
贼婆χ
2楼-- · 2019-03-08 06:00

It turns out that this is possible using log4j after all(tested using v1.2.16), thanks to Tomasz Nurkiewicz for pointing me to LogBack. The feature, ConversionWord, is available using the EnhancedPatternLayout layout.

From the javadoc

... For example, for the category name "alpha.beta.gamma" the pattern %c{2} will output the last two elements ("beta.gamma"), %c{-2} will remove two elements leaving "gamma", %c{1.} will output "a.b.gamma" ...

I'm using JBoss and had to upgrade log4j and use the above layout.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-08 06:06

Artifactory uses Logback:

Projects known to rely on logback:

  • [...]

  • Artifactory

which has this nice feature called Conversion Word:

|Conversion specifier | Logger name                | Result                    |
|---------------------|:--------------------------:| -------------------------:|
|%logger              | mainPackage.sub.sample.Bar | mainPackage.sub.sample.Bar|
|%logger{0}           | mainPackage.sub.sample.Bar | Bar                       |
|%logger{5}           | mainPackage.sub.sample.Bar | m.s.s.Bar                 |
|%logger{10}          | mainPackage.sub.sample.Bar | m.s.s.Bar                 |
|%logger{15}          | mainPackage.sub.sample.Bar | m.s.sample.Bar            |
|%logger{16}          | mainPackage.sub.sample.Bar | m.sub.sample.Bar          |
|%logger{26}          | mainPackage.sub.sample.Bar | mainPackage.sub.sample.Bar|

* I miss tables in SO markdown sooo much...

查看更多
登录 后发表回答