为了在Java中使用logger,现在我使用如下代码:
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("c:\\MyLogFile.log", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.log(Level.WARNING,"My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但是为每个类文件添加以下代码总是会让我有点困扰:
Logger l = Logger.getLogger("MyLog");
我该如何重构这种重复呢?
发布于 2016-07-04 12:40:30
登录每个类文件是一种正确的方式,尽管它看起来有点冗余。
日志记录的重要功能是记录异常。如果我们想要直接找到异常发生的位置,我们应该知道类名和方法名。
但是您可能在捕获异常时忘记了记录日志。
发布于 2016-07-04 22:56:23
发布于 2018-08-20 02:16:18
您可以使用项目lombok来完成此操作:
下面是他们网页上的例子,如果它曾经不可用的话。要清楚的是,它仍然在你的结果字节码中生成语句,但它停止了bolierplate,现在你将有一个更小的语句,但在它的马的课程,但我目前工作的项目团队喜欢它。
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
@Log
public class LogExample {
public static void main(String... args) {
log.error("Something's wrong here");
}
}
@Slf4j
public class LogExampleOther {
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
@CommonsLog(topic="CounterLog")
public class LogExampleCategory {
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
Vanilla Java
public class LogExample {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
public static void main(String... args) {
log.error("Something's wrong here");
}
}
public class LogExampleOther {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
public class LogExampleCategory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
https://stackoverflow.com/questions/38176285
复制相似问题