Log4j2 Multiple Appenders Configuration¶
Log4j2 supports directing log events from specific components to distinct outputs by configuring multiple appenders and associating them with specific named loggers.^[600-developer__java__3-party__java-log4j2.md]
Logger Definition¶
To utilize separate appenders, specific logger instances must be defined in the code, typically with unique names corresponding to different parts of the application (e.g., "main", "bolt", "spout").^[600-developer__java__3-party__java-log4j2.md:21-26]
public class LogUtils {
public static final Logger main = LoggerFactory.getLogger("main");
public static final Logger bolt = LoggerFactory.getLogger("bolt");
public static final Logger spout = LoggerFactory.getLogger("spout");
}
XML Configuration¶
The log4j2.xml file defines the appenders (the destinations) and links them to the specific loggers defined in the code.^[600-developer__java__3-party__java-log4j2.md:28-89]
Appenders¶
The <Appenders> section declares the available output targets.^[600-developer__java__3-party__java-log4j2.md:34-68] A common setup includes a Console appender for standard output and multiple RollingFile appenders for writing to the file system.
- Console: Outputs logs to
SYSTEM_OUT.^[600-developer__java__3-party__java-log4j2.md:36-38] - RollingFile: Writes to a specific file (e.g.,
C:/logs/main.log) and rolls over based on a size policy (e.g.,19500KB) or time-based pattern.^[600-developer__java__3-party__java-log4j2.md:40-48]
Loggers¶
The <Loggers> section connects the code-defined loggers to the configured appenders.^[600-developer__java__3-party__java-log4j2.md:70-88]
- Named Loggers: For each named logger (e.g., "main", "bolt"), the
additivityattribute should be set tofalseto prevent log events from being passed up to the root logger.^[600-developer__java__3-party__java-log4j2.md:72-80] An<AppenderRef>is then used to specify which appender receives the logs for that specific logger. - Root Logger: The
<Root>logger typically captures events not caught by specific loggers or serves as a default output (often to the console).^[600-developer__java__3-party__java-log4j2.md:84-87]
Sources¶
- 600-developer__java__3-party__java-log4j2.md