Log4j2 separate log files by module name

2019-07-17 01:27发布

问题:

I want to write log files based on module name. for ex. one log file for user management module and one for products module etc.

My project package structure looks like below;

com.mycompany.service.user
com.mycompany.service.product
com.mycompany.controller.user
com.mycompany.controller.product
...

I want to write log messages from com.mycompany.*.user (com.mycompany.service.user and com.mycompany.controller.user) to com.mycompany.user.log file, and com.mycompany.*.product to com.mycompany.user.log file.

I know I can create loggers like bellow

<logger name="com.mycompany.service.user" level="INFO">
  <AppenderRef ref="AppenderUsers" />
</logger>
<logger name="com.mycompany.controller.user" level="INFO">
  <AppenderRef ref="AppenderUsers" />
</logger>
...

But this way I have to add so many loggers. Cant I use wildcard * or ** or regex to logger name somethihng like this?

<logger name="com.mycompany.*.user" level="INFO">
  <AppenderRef ref="AppenderUsers" />
</logger>

Or is there any way to do this?

回答1:

Finally I have solved this by writing a Custom Filter Plugin. I have used same approach used in Regex filter. But Regex filter, match given regex with Message content. But I have written a filter to match regex with class name.

I have describe this in my blog post. http://rohithag.blogspot.com/



回答2:

I suggest you raise this as a feature request in the log4j2 Jira issue tracker.