Lombok之@Slf4j
之前用lombok只知道有@Getter,@Setter,@Data,@NoArgsConstructor,@AllArgsConstructor,@EqualsAndHashCode,@ToString这些注解,
今天学习Slf4j发现lombok也对其做了简化。
一、正常Slf4j的用法:
public class Main {
static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
logger.info("Start process {}...", Main.class.getName());
try {
"".getBytes("invalidCharsetName");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
logger.info("Process end.");
}
}
二、使用Lombok中的@Slf4j注解:
@Slf4j
public class Main {
public static void main(String[] args) {
log.info("Start process {}...", Main.class.getName());
try {
"".getBytes("invalidCharsetName");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
log.info("Process end.");
}
}
是不是简单很多?
我看们一下Slf4j注解的源码:
package lombok.extern.slf4j;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Causes lombok to generate a logger field.
*
* Complete documentation is found at <a href="https://projectlombok.org/features/log">the project lombok features page for lombok log annotations</a>.
*
* Example:
*
* @Slf4j
* public class LogExample {
* }
*
* will generate:
*
* public class LogExample {
* private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
* }
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface XSlf4j {
/** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */
String topic() default "";
}
其中注释部分提到了使用@Slf4j注解会自动生成
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
这样我们就可以直接使用log.error(),log.info()等语句打印日志了。
我们还可以指定topic,使日志打印更加灵活 比如:
import lombok.extern.slf4j.Slf4j;
// 使用默认topic(空字符串)
@Slf4j
public class UserService {
public void createUser() {
log.info("User created"); // 日志记录器名称自动为"UserService"
}
}
// 自定义topic
@Slf4j(topic = "security")
public class AuthService {
public void authenticate() {
log.info("Authentication started"); // 日志记录器名称为"security"
}
}