why can't I log method name and code line in log4j when I extend log4j

我们两清 提交于 2019-11-30 16:41:07

I think there are two questions here:

  1. What is a good way to create a custom or extended logger that can log location information correctly?
  2. How can the application dynamically select the target appender at runtime?

1. Custom Loggers

How Log4j can print the method name and line number is by walking the stack trace (for each event) and finding the class/method in the application that called the logger. It can do this because Log4j knows the fully qualified class name (FQCN) of the logger. With a custom logger this requires a different FQCN and also requires that the stack trace has the same structure: the custom logger FQCN and the application class/method are the same number of lines apart in the stack trace as with the standard Log4j logger. This can be tricky to get right.

Would it be possible for you to achieve your goals with a logger wrapper? Log4j comes with a Logger wrapper generator tool. This tool was originally meant to support custom log levels and is documented on the Custom Log Levels page of the manual.

The generated logger code will take care of the FQCN and you can use it as a base for the further enhancements you have in mind.

2. Dynamically Selecting an Appender at Runtime

This requirement is common enough that Log4j2 provides a built-in solution, so you should not need to create a custom logger for this.

The standard way to solve this is to configure a Routing Appender. This appender can route log events to a set of predefined appenders or it can dynamically add new appenders if necessary.

The manual page has three examples, but the example in the FAQ page ("How do I dynamically write to separate log files?") may be a fairly close fit to your requirements. That example uses the ThreadContext map to control which log file subsequent events (in the current thread) get logged to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!