org.springframework.boot.logging.LogLevel Java Examples

The following examples show how to use org.springframework.boot.logging.LogLevel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LogWriter.java    From java-starthere with MIT License 6 votes vote down vote up
public static void write(Class clazz, LogLevel logLevel, String message)
{
    switch (logLevel)
    {
        case TRACE:
            logger.trace(message);
            break;
        case DEBUG:
            logger.debug(message);
            break;
        case INFO:
            logger.info(message);
            break;
        case WARN:
            logger.warn(message);
            break;
        case ERROR:
            logger.error(message);
            break;
        default:
            logger.warn("No suitable log level found");
            break;
    }
}
 
Example #2
Source File: Logger.java    From logger-spring-boot with Apache License 2.0 6 votes vote down vote up
private void log(org.slf4j.Logger logger, LogLevel level, String message, Object... args) {
    Objects.requireNonNull(level, "LogLevel must not be null.");
    switch (level) {
        case TRACE:
            logger.trace(message, args);
            break;
        case DEBUG:
            logger.debug(message, args);
            break;
        case INFO:
            logger.info(message, args);
            break;
        case WARN:
            logger.warn(message, args);
            break;
        case ERROR:
        case FATAL:
            logger.error(message, args);
            break;
        default:
            break;
    }
}
 
Example #3
Source File: LogValidator.java    From eclair with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(Method method, T target) throws AnnotationUsageException {
    LogLevel expectedLevel = AnnotationAttribute.LEVEL.extract(target);
    LogLevel ifEnabledLevel = AnnotationAttribute.IF_ENABLED.extract(target);
    if (ifEnabledLevel.ordinal() >= expectedLevel.ordinal() && ifEnabledLevel != OFF) {
        throw new AnnotationUsageException(method,
                format("'ifEnabled = %s' should be more strict than 'level = %s'", ifEnabledLevel, expectedLevel),
                "Correct specified levels relation or replace 'ifEnabled' by default value 'OFF'",
                target);
    }

    String printerName = AnnotationAttribute.PRINTER.extract(target);
    if (StringUtils.hasText(printerName)) {
        Printer printer = printerResolver.resolve(printerName);
        if (isNull(printer)) {
            throw new AnnotationUsageException(method,
                    format("Unknown printer '%s'", printerName),
                    "Use correct bean name or alias to specify 'printer'",
                    target);
        }
    }
}
 
Example #4
Source File: Logger.java    From logger-spring-boot with Apache License 2.0 6 votes vote down vote up
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) {
    Objects.requireNonNull(level, "LogLevel must not be null.");
    switch (level) {
        case TRACE:
            return logger.isTraceEnabled();
        case DEBUG:
            return logger.isDebugEnabled();
        case INFO:
            return logger.isInfoEnabled();
        case WARN:
            return logger.isWarnEnabled();
        case ERROR:
        case FATAL:
            return logger.isErrorEnabled();
        default:
            throw new IllegalArgumentException("LogLevel must be one of the enabled levels.");
    }
}
 
Example #5
Source File: PrintLogger.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@NacosConfigListener(dataId = "${nacos.example.listener.data-id}", timeout = 5000)
public void onChange(String newLog) throws Exception {
	Properties properties = new DefaultPropertiesConfigParse().parse(newLog);
	for (Object t : properties.keySet()) {
		String key = String.valueOf(t);
		if (key.startsWith(LOGGER_TAG)) {
			String strLevel = properties.getProperty(key, "info");
			LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
			loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
			logger.info("{}:{}", key, strLevel);
		}
	}
}
 
Example #6
Source File: ActuatorCommand.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Loggers method
 *
 * @param action      action to make
 * @param loggerName  logger name for get or configure
 * @param loggerLevel logger level for configure
 * @return loggers
 */
@ShellMethod(key = "loggers", value = "Display or configure loggers.")
@ShellMethodAvailability("loggersAvailability")
public Object loggers(
        @ShellOption(value = {"-a", "--action"}, help = "Action to perform", defaultValue = "list") LoggerAction action,
        @ShellOption(value = {"-n", "--name"}, help = "Logger name for configuration or display", defaultValue =
                ShellOption.NULL) String loggerName,
        @ShellOption(value = {"-l", "--level"}, help = "Logger level for configuration", defaultValue =
                ShellOption.NULL) LogLevel loggerLevel) {
    if ((action == LoggerAction.get || action == LoggerAction.conf) && loggerName == null) {
        throw new IllegalArgumentException("Logger name is mandatory for '" + action + "' action");
    }
    switch (action) {
        case get:
            LoggersEndpoint.LoggerLevels levels = loggers.loggerLevels(loggerName);
            return "Logger named [" + loggerName + "] : [configured: " + levels.getConfiguredLevel() + "]";
        case conf:
            if (loggerLevel == null) {
                throw new IllegalArgumentException("Logger level is mandatory for '" + action + "' action");
            }
            loggers.configureLogLevel(loggerName, loggerLevel);
            return "Logger named [" + loggerName + "] now configured to level [" + loggerLevel + "]";
        default:
            // list
            return loggers.loggers();
    }
}
 
Example #7
Source File: LoggingRebinder.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private LogLevel resolveLogLevel(String level) {
	String trimmedLevel = level.trim();
	if ("false".equalsIgnoreCase(trimmedLevel)) {
		return LogLevel.OFF;
	}
	return LogLevel.valueOf(trimmedLevel.toUpperCase(Locale.ENGLISH));
}
 
Example #8
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logFatalError() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL);
    logger.log(LogLevel.FATAL, "logger name", "fatal message", new Exception("error message"));
    Pattern pattern = Pattern.compile("ERROR logger name - fatal message.*java.lang.Exception: error message",
            Pattern.DOTALL | Pattern.MULTILINE);
    assertTrue(pattern.matcher(capture.toString()).find());
}
 
Example #9
Source File: LoggingDslTests.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Test
void changeDefaultROOTLogLevel() {
	var app = application(it -> it.logging(log -> log.level(LogLevel.DEBUG)));
	app.run();
	var loggingSystem = LoggingSystem.get(LoggingDslTests.class.getClassLoader());
	assertEquals(LogLevel.DEBUG, loggingSystem.getLoggerConfiguration("ROOT").getEffectiveLevel());
}
 
Example #10
Source File: LogEventPublisher.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 发布自定义日志事件
 *
 * @param level       日志级别
 * @param prefix      日志前缀
 * @param description 日志描述
 */
public static void publishCustomLogEvent(LogLevel level, String prefix, String description) {
	HttpServletRequest request = WebUtil.getRequest();
	CustomLogModel model = new CustomLogModel(level);
	model.setPrefix(prefix);
	model.setDescription(description);
	Map<String, Object> event = new HashMap<>(16);
	event.put(LogConstants.EVENT_LOG_KEY, model);
	event.put(LogConstants.EVENT_REQUEST_KEY, request);
	SpringUtil.publishEvent(new CustomLogEvent(event));
}
 
Example #11
Source File: LogbackLoggingSystem.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
private LoggerConfiguration getLoggerConfiguration(ch.qos.logback.classic.Logger logger) {
	if (logger == null) {
		return null;
	}
	LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel());
	LogLevel effectiveLevel = LEVELS.convertNativeToSystem(logger.getEffectiveLevel());
	String name = logger.getName();
	if (!StringUtils.hasLength(name) || Logger.ROOT_LOGGER_NAME.equals(name)) {
		name = ROOT_LOGGER_NAME;
	}
	return new LoggerConfiguration(name, level, effectiveLevel);
}
 
Example #12
Source File: LogbackLoggingSystem.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public void setLogLevel(String loggerName, LogLevel level) {
	ch.qos.logback.classic.Logger logger = getLogger(loggerName);
	if (logger != null) {
		logger.setLevel(LEVELS.convertSystemToNative(level));
	}
}
 
Example #13
Source File: LoggerConfiguration.java    From apollo-use-cases with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void refreshLoggingLevels() {
  Set<String> keyNames = config.getPropertyNames();
  for (String key : keyNames) {
    if (containsIgnoreCase(key, LOGGER_TAG)) {
      String strLevel = config.getProperty(key, "info");
      LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
      loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
      logger.info("{}:{}", key, strLevel);
    }
  }
}
 
Example #14
Source File: ExampleTest.java    From eclair with Apache License 2.0 5 votes vote down vote up
private Map<String, List<LogLevel>> groupLevels(String loggerName) {
    return exampleAppender.getLoggerEvents(loggerName).entrySet().stream()
            .collect(groupingBy(
                    o -> exampleTableBuilder.buildSampleCell(o.getValue()),
                    LinkedHashMap::new,
                    mapping(identity(), toList())
            )).entrySet().stream().collect(toMap(
                    Map.Entry::getKey,
                    o -> o.getValue().stream().map(Map.Entry::getKey).collect(toList()),
                    (logLevels, logLevels2) -> {
                        throw new RuntimeException();
                    },
                    LinkedHashMap::new
            ));
}
 
Example #15
Source File: ExampleTest.java    From eclair with Apache License 2.0 5 votes vote down vote up
private void invoke(Runnable runnable, LogLevel level) {
    loggingSystem.setLogLevel(ROOT_LOGGER_NAME, level);
    exampleAppender.setLevel(level);
    try {
        runnable.run();
    } catch (Throwable e) {
        // do nothing
    }
}
 
Example #16
Source File: ExampleTableBuilder.java    From eclair with Apache License 2.0 5 votes vote down vote up
private String buildLevelsCell(List<LogLevel> logLevels) {
    StringBuilder payload = new StringBuilder(" ");
    payload.append(logLevels.size() > 2 ? buildCroppedLevelsCell(logLevels) : buildFullLevelsCell(logLevels));
    while (payload.length() < LEVELS_CELL_WIDTH) {
        payload.append(" ");
    }
    return payload.toString();
}
 
Example #17
Source File: LogWriter.java    From cerebro with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void write(Class clazz, LogLevel logLevel, String message) {
    Logger logger = LoggerFactory.getLogger(clazz);

    switch (logLevel) {
    case TRACE:
        logger.trace(message);
        break;
    case DEBUG:
        logger.debug(message);
        break;
    case INFO:
        logger.info(message);
        break;
    case WARN:
        logger.warn(message);
        break;
    case ERROR:
        logger.error(message);
        break;
    case FATAL:
        Marker marker = MarkerFactory.getMarker("FATAL");
        logger.error(marker, message);
        break;
    default:
        logger.warn("No suitable log level found");
        break;
    }
}
 
Example #18
Source File: LoggerInterceptor.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
private void log(LogLevel level, String message, ProceedingJoinPoint joinPoint, Loggable loggable, Object... args) {
    if (loggable.name().isEmpty()) {
        logger.log(level, ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass(), message, args);
    } else {
        logger.log(level, loggable.name(), message, args);
    }
}
 
Example #19
Source File: LogLevelConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
public void changeLogLevel(String loggerName, LogLevel level) {
	try {
		loggingSystem.setLogLevel(loggerName, level);
	} catch (Exception e) {
		// TODO: handle exception
	}
}
 
Example #20
Source File: LoggersHtmlEndpoint.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@RequestMapping(
        value = "${edison.application.management.base-path:/internal}/loggers",
        consumes = APPLICATION_FORM_URLENCODED_VALUE,
        produces = TEXT_HTML_VALUE,
        method = POST)
public RedirectView post(@ModelAttribute("name") String name,
                         @ModelAttribute("level") String level,
                         HttpServletRequest httpServletRequest) {
    final LogLevel logLevel = level == null ? null : valueOf(level.toUpperCase());
    loggersEndpoint.configureLogLevel(name, logLevel);
    return new RedirectView(String.format("%s%s/loggers", baseUriOf(httpServletRequest), applicationProperties.getManagement().getBasePath()));
}
 
Example #21
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logTraceError() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE);
    logger.log(LogLevel.TRACE, "logger name", "trace message", new Exception("error message"));
    Pattern pattern = Pattern.compile("TRACE logger name - trace message.*java.lang.Exception: error message",
            Pattern.DOTALL | Pattern.MULTILINE);
    assertTrue(pattern.matcher(capture.toString()).find());
}
 
Example #22
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logErrorError() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.ERROR);
    logger.log(LogLevel.ERROR, "logger name", "error message", new Exception("error message"));
    Pattern pattern = Pattern.compile("ERROR logger name - error message.*java.lang.Exception: error message",
            Pattern.DOTALL | Pattern.MULTILINE);
    assertTrue(pattern.matcher(capture.toString()).find());
}
 
Example #23
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logDebug() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG);
    logger.log(LogLevel.DEBUG, "logger name", "debug message");
    assertThat(capture.toString(), containsString("DEBUG logger name - debug message"));
}
 
Example #24
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logDebugError() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG);
    logger.log(LogLevel.DEBUG, "logger name", "debug message", new Exception("error message"));
    Pattern pattern = Pattern.compile("DEBUG logger name - debug message.*java.lang.Exception: error message",
            Pattern.DOTALL | Pattern.MULTILINE);
    assertTrue(pattern.matcher(capture.toString()).find());
}
 
Example #25
Source File: DeployerApplication.java    From spring-cloud-cli with Apache License 2.0 5 votes vote down vote up
private void quiet() {
	try {
		LogbackLoggingSystem.get(ClassUtils.getDefaultClassLoader())
				.setLogLevel("ROOT", LogLevel.OFF);
	}
	catch (Exception e) {
		logger.error("Unable to turn of ROOT logger for quiet()", e);
	}
}
 
Example #26
Source File: LoggerTest.java    From logger-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void logTrace() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE);
    logger.log(LogLevel.TRACE, "logger name", "trace message");
    assertThat(capture.toString(), containsString("TRACE logger name - trace message"));
}
 
Example #27
Source File: CustomLogModel.java    From magic-starter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public CustomLogModel(LogLevel level) {
	super(LogType.CUSTOM, level);
}
 
Example #28
Source File: LogLevelConfig.java    From pmq with Apache License 2.0 4 votes vote down vote up
private LogLevel coerceLogLevel(String level) {
	if ("false".equalsIgnoreCase(level)) {
		return LogLevel.OFF;
	}
	return LogLevel.valueOf(level.toUpperCase());
}
 
Example #29
Source File: LoggerInterceptor.java    From logger-spring-boot with Apache License 2.0 4 votes vote down vote up
private boolean isLevelEnabled(ProceedingJoinPoint joinPoint, Loggable loggable) {
    return loggable.name().isEmpty()
            ? logger.isEnabled(LogLevel.WARN,
            ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass())
            : logger.isEnabled(LogLevel.WARN, loggable.name());
}
 
Example #30
Source File: SimpleLogger.java    From eclair with Apache License 2.0 4 votes vote down vote up
/**
 * Performs the logging of 'in'-event (beginning of method execution).
 *
 * @param invocation current loggable method invocation
 * @param methodLog  definition of invoked method logging
 */
@Override
protected void logIn(MethodInvocation invocation, MethodLog methodLog) {
    String loggerName = getLoggerName(invocation);
    LogLevel level = null;

    // initialize 'inLog' attributes
    InLog inLog = methodLog.getInLog();
    boolean isInLogLogEnabled = false;
    boolean isInLogVerboseLogEnabled = false;
    if (nonNull(inLog)) {
        LogLevel inLogLevel = inLog.getLevel();
        isInLogLogEnabled = (inLogLevel != OFF) && isLogEnabled(loggerName, expectedLevelResolver.apply(inLog));
        if (isInLogLogEnabled) {
            level = inLogLevel;
            isInLogVerboseLogEnabled = isLogEnabled(loggerName, inLog.getVerboseLevel());
        }
    }

    StringBuilder builder = new StringBuilder();
    boolean isParameterLogVerboseFound = false;
    boolean isParameterLogSkippedFound = false;
    Object[] arguments = invocation.getArguments();
    for (int a = 0; a < arguments.length; a++) {
        ParameterLog parameterLog = methodLog.getParameterLogs().get(a);
        boolean isParameterLogDefined = nonNull(parameterLog);

        // filter argument
        if (isParameterLogDefined) {
            LogLevel parameterLogLevel = parameterLog.getLevel();
            if (parameterLogLevel == OFF || !isLogEnabled(loggerName, expectedLevelResolver.apply(parameterLog))) {
                isParameterLogSkippedFound = true;
                continue;
            }
            if (!isInLogLogEnabled) {
                if (isNull(level) || parameterLogLevel.ordinal() > level.ordinal()) {
                    level = parameterLogLevel;
                }
            }
        } else if (!isInLogVerboseLogEnabled) {
            isParameterLogSkippedFound = true;
            continue;
        }

        // print delimiter
        if (isParameterLogVerboseFound) {
            builder.append(", ");
        } else {
            builder.append(" ");
            isParameterLogVerboseFound = true;
        }

        // print parameter name
        if (!isParameterLogDefined || isLogEnabled(loggerName, parameterLog.getVerboseLevel())) {
            String parameterName = methodLog.getParameterNames().get(a);
            if (nonNull(parameterName)) {
                builder.append(parameterName).append("=");
            } else if (isParameterLogSkippedFound) {
                builder.append(Integer.toString(a)).append("=");
            }
        }

        // print parameter value
        Object argument = arguments[a];
        if (isNull(argument)) {
            builder.append((String) null);
        } else if (isParameterLogDefined) {
            builder.append(printArgument(parameterLog.getPrinter(), argument));
        } else {
            builder.append(printArgument(inLog.getPrinters().get(a), argument));
        }
    }

    if (isInLogLogEnabled || isParameterLogVerboseFound) {
        String message = IN + builder.toString();
        loggerFacadeFactory.getLoggerFacade(loggerName).log(level, message);
    }
}