一、添加Maven依赖
<dependencies> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> </dependencies>
二、自定义Appender
package com.weidai.zm.logger; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.layout.PatternLayout; import java.io.Serializable; /** * @author : zhangyanqing * @time : 2017/12/10 * @desc : 自定义Appender */ @Plugin(name="ConsoleArea", category = "core",elementType = "appender", printObject = true) public class MyAppender extends AbstractAppender{ public MyAppender(final String name, final Filter filter, final Layout<? extends Serializable> layout, final boolean ignoreExceptions) { super(name, filter, layout,ignoreExceptions); } @Override public void append(LogEvent logEvent) { System.out.println("[My Appender] "+logEvent.getLoggerName()+"=>"+logEvent.getMessage()); } @PluginFactory public static MyAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter, @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginAttribute("ignoreExceptions") boolean ignoreExceptions) { if (name == null) { LOGGER.error("No name provided for MyCustomAppenderImpl"); return null; } if (layout == null) { layout = PatternLayout.createDefaultLayout(); } return new MyAppender(name, filter, layout, ignoreExceptions); } }
三、log4j2.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <properties> <Property name="console-pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%level] %logger{36} - %msg%n</Property> </properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="${console-pattern}" /> </Console> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console" /> </Root> </Loggers> </Configuration>
四、测试代码
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * @author : zhangyanqing * @time : 2017/12/9 * @desc : 根控制器日志测试 */ public class ConsoleLoggerTest { public static final Logger LOGGER = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME); public static void main(String[] args){ LOGGER.trace("trace level"); LOGGER.debug("debug level"); LOGGER.info("info level"); LOGGER.warn("warn level"); LOGGER.error("error level"); LOGGER.fatal("fatal level"); } }