Spring基础:快速入门spring boot(4):使用slf4j输出日志

本篇文章将在将介绍如何使用slf4j。

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第1张图片

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第2张图片

Slf4J是Simple Logging Facade for Java的缩写,从其全称即可清晰地看出其定位为日志系统的Facade,其实它就是在不同的日志系统之上封装的门面,便于移植和更换,降低了日志和系统的直接耦合。

使用前提

为了使用slf4j,一般需要import的主要有slf4j的Logger和LoggerFactory。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

LoggerFactory就是一个普通的工厂模式的实现,可以追到其源码的主要实现部分如下:

    public static ILoggerFactory getILoggerFactory() {
        if(INITIALIZATION_STATE == 0) {
            Class var0 = LoggerFactory.class;
            synchronized(LoggerFactory.class) {
                if(INITIALIZATION_STATE == 0) {
                    INITIALIZATION_STATE = 1;
                    performInitialization();
                }
            }
        }

        switch(INITIALIZATION_STATE) {
        case 1:
            return SUBST_FACTORY;
        case 2:
            throw new IllegalStateException("org.slf4j.LoggerFactory could not be successfully initialized. See also http://www.slf4j.org/codes.html#unsuccessfulInit");
        case 3:
            return StaticLoggerBinder.getSingleton().getLoggerFactory();
        case 4:
            return NOP_FALLBACK_FACTORY;
        default:
            throw new IllegalStateException("Unreachable code");
        }
    }

使用方式

取得

private final Logger logger = LoggerFactory.getLogger(this.getClass());

使用

    logger.info("## Info  Information ##: {}", name);
    logger.warn("## Warn  Information ##: {}", name);
    logger.error("## Error Information ##: {}", name);

修改DemoApplication

package com.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@SpringBootApplication
public class DemoApplication {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  private final AtomicLong counter = new AtomicLong();
  private final String templateStr="Hello, %s, Welcome to Spring Boot ...";

  @RequestMapping("/greeting")
  public User greeting(@RequestParam(value="name",defaultValue = "World") String name){
    logger.info("## Info  Information ##: {}", name);
    logger.warn("## Warn  Information ##: {}", name);
    logger.error("## Error Information ##: {}", name);
    return new User(counter.incrementAndGet(),String.format(templateStr,name));
  }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Console输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

2016-12-08 21:13:36.786  INFO 3096 --- [           main] com.example.DemoApplication              : Starting DemoApplication on vcc-PC with PID 3096 (C:\Users\Administrator\IdeaProjects\demo\target\classes started by Administrator in C:\Users\Administrator\IdeaProjects\demo)
2016-12-08 21:13:36.786  INFO 3096 --- [           main] com.example.DemoApplication              : No active profile set, falling back to default profiles: default
2016-12-08 21:13:36.848  INFO 3096 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Thu Dec 08 21:13:36 CST 2016]; root of context hierarchy
2016-12-08 21:13:38.411  INFO 3096 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-08 21:13:38.426  INFO 3096 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-12-08 21:13:38.426  INFO 3096 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-08 21:13:38.536  INFO 3096 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-12-08 21:13:38.536  INFO 3096 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1688 ms
2016-12-08 21:13:38.676  INFO 3096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-08 21:13:38.692  INFO 3096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-08 21:13:38.692  INFO 3096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-08 21:13:38.692  INFO 3096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-08 21:13:38.692  INFO 3096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-08 21:13:38.972  INFO 3096 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Thu Dec 08 21:13:36 CST 2016]; root of context hierarchy
2016-12-08 21:13:39.050  INFO 3096 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public com.example.User com.example.DemoApplication.greeting(java.lang.String)
2016-12-08 21:13:39.050  INFO 3096 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntityString, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-12-08 21:13:39.050  INFO 3096 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-12-08 21:13:39.082  INFO 3096 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 21:13:39.082  INFO 3096 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 21:13:39.113  INFO 3096 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 21:13:39.253  INFO 3096 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-12-08 21:13:39.316  INFO 3096 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-08 21:13:39.316  INFO 3096 --- [           main] com.example.DemoApplication              : Started DemoApplication in 3.109 seconds (JVM running for 3.645)

结果确认

画面刷新

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第3张图片

log输出确认

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第4张图片

参数绑定刷新

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第5张图片

log输出确认

Spring基础:快速入门spring boot(4):使用slf4j输出日志_第6张图片

你可能感兴趣的:(spring,spring快速入门)