Sentinel-Log(JUL)
在sentinel中日志的处理都是通过RecordLog来进行,那么sentinel是如何日志实现呢?
如果业务代码中引入了sentinel-logging的话,那么会具体依赖logback等。如果没有,则使用java自带的日志框架JUL实现。对JUL的了解可以查看文章。
static { try { // Load user-defined logger implementation first. // 具体可以参考sentinel-logging中的代码 logger = LoggerSpiProvider.getLogger(LOGGER_NAME); if (logger == null) { // If no customized loggers are provided, we use the default logger based on JUL. logger = new JavaLoggingAdapter(LOGGER_NAME, DEFAULT_LOG_FILENAME); } } catch (Throwable t) { System.err.println("Error: failed to initialize Sentinel RecordLog"); t.printStackTrace(); } }
接下来具体介绍sentinel是如何实现JUL的。
在logger初始化的时候定义了logHander,具体的handler都是自定义的,主要是输出文件DataFileLogHandler和控制台ConsoleHandler
public class JavaLoggingAdapter extends BaseJulLogger implements Logger { private final String loggerName; private final String fileNamePattern; private final java.util.logging.Logger julLogger; private final Handler logHandler; public JavaLoggingAdapter(String loggerName, String fileNamePattern) { AssertUtil.assertNotBlank(loggerName, "loggerName cannot be blank"); AssertUtil.assertNotBlank(fileNamePattern, "fileNamePattern cannot be blank"); this.loggerName = loggerName; this.fileNamePattern = fileNamePattern; this.julLogger = java.util.logging.Logger.getLogger(loggerName); this.logHandler = makeLoggingHandler(fileNamePattern, julLogger); }
以及打印格式CspFormatter,并设置默认的日志级别为INFO ,具体读者可以查看源代码makeLoggingHandler,这里就不阐述了 。
当打印Info日志的时候,执行 log(julLogger, logHandler, Level.INFO, msg, e)
protected void log(Logger logger, Handler handler, Level level, String detail, Throwable throwable) { if (detail == null) { return; } /** * 移除非handler的其他handler,并添加handler */ disableOtherHandlers(logger, handler); logger.log(level, detail, throwable); }