现在公司工作中使用的日志工具是slf4j+logback。
初始化工具类实现如下:
public class LogUtil { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(LogUtil.class); public static final String __CONF_DIR__ = "conf"; public static void loadLogbackConfiguration(String confDir) { try { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); File file = new File(confDir + "/logback.xml"); if (file.exists()) { configurator.doConfigure(file); if (LOGGER.isInfoEnabled()) { LOGGER.info("loading logback conf from:{}", file.getAbsolutePath()); } } else { URL url = org.apache.commons.configuration.ConfigurationUtils.locate("logback.xml"); configurator.doConfigure(url); if (LOGGER.isInfoEnabled()) { LOGGER.info("loading logback conf from:{}", url); } } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } catch (JoranException e) { LOGGER.error("failed to load logback config from:" + confDir, e); } } public static void main(String[] args){ LogUtil.loadLogbackConfiguration(LogUtil.__CONF_DIR__); LOGGER.debug("debug..."); LOGGER.error("error..."); } }
基本过程就是找到并加载logback.xml文件,初始化日志系统。然后就可以使用logger.debug或者logger.error等方法输出日志,其中用到了commons-configuration的类库查找logback.xml文件。
加载logback.xml的JoranConfigurator类是logback内部集成的配置工具。
另外,关于logback的配置及使用我会单独写一篇关于logback的博客总结一下。
希望对看到的人有所帮助。