建立基於Maven的工程,在pom.xml中添加以下內容 html
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency>
如今你能夠在你的Java代碼中這樣使用Logger java
package deng; import org.slf4j.*; public class Hello { static Logger LOGGER = LoggerFactory.getLogger(Hello.class); public static void main(String[] args) { for (int i = 0; i < 10; i++) if (i % 2 == 0) LOGGER.info("Hello {}", i); else LOGGER.debug("I am on index {}", i); } }
以上代碼能夠編譯經過,可是當你運行它時,你會看到這樣的輸出: api
bash> java deng.Hello SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
加入logback的依賴: bash
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency>
src/main/resources/logback.xml(根目錄建立該文件)
app
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="deng" level="DEBUG"/> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>