注解@Slf4j

介绍

  常见的Slf4j日志打印有两种方式,分别为传统方式和注解方式。html

一、传统方式

示例:web

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.HelloService;

@RestController
@RequestMapping("/Test")
public class HelloWorld {
    @Autowired
    private HelloService helloService;

    private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    @GetMapping("/hello")
    public String sayHello(){
        logger.info("hello Sfl4j + logback......");
        return helloService.sayHello();
    }
}

二、注解方式

<1>maven依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<2>IDE安装lombok插件

(若是注解@Slf4j注入后找不到变量log,那就给IDE安装lombok插件)spring

经常使用IDEA安装lombok插件,app

Settings→Plugins→Browse repositories→lombok pluginmaven

在线安装不行,采用本地安装,能够参考:spa

http://www.javashuo.com/article/p-xxbbfsru-bb.html插件

<3>使用示例

package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.HelloService;

@Slf4j
@RestController
@RequestMapping("/Test")
public class HelloWorld {
    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHello(){
        log.info("hello @Sfl4j + logback......");
        return helloService.sayHello();
    }
}

三、小结

  注解方式较传统方式更加简单快捷,最直接的便利就是不用每次新建一个类时都要建立 logger,即:日志

 private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);
相关文章
相关标签/搜索