一、依賴包準備
//slf4j專案提供 compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' //log4j2專案提供 compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.8.2' compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.2' compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.8.2'
二、使用slf4j
protected static Logger logger = LoggerFactory.getLogger(YourClass.class);
注意import類的選擇
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
三、初始化log4j2
1. 方式一 預設路徑
將log4j2.xml放到src目錄下,Log4j2預設會去該位置讀取。
2. 方式二 指定路徑
LoggerContext logContext = (LoggerContext) LogManager.getContext(false); File conFile = new File("conf/log4j2.xml"); logContext.setConfigLocation(conFile.toURI()); logContext.reconfigure(); logger.debug("hello world...{}","How are you");
此處import類的選擇
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
至此,全部配置好了。執行一下試試吧。