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 Project: java-starthere   Author: LambdaSchool   File: LogWriter.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: Logger.java    License: 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 #3
Source Project: eclair   Author: TinkoffCreditSystems   File: LogValidator.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: Logger.java    License: 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 #5
Source Project: pmq   Author: ppdaicorp   File: LogLevelConfig.java    License: 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 #6
Source Project: magic-starter   Author: xkcoding   File: LogEventPublisher.java    License: 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 #7
Source Project: spring-fu   Author: spring-projects-experimental   File: LoggingDslTests.java    License: 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 #8
Source Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 Project: spring-cloud-commons   Author: spring-cloud   File: LoggingRebinder.java    License: 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 #10
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ActuatorCommand.java    License: 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 #11
Source Project: super-cloudops   Author: wl4g   File: LogbackLoggingSystem.java    License: 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 Project: super-cloudops   Author: wl4g   File: LogbackLoggingSystem.java    License: 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 Project: apollo-use-cases   Author: ctripcorp   File: LoggerConfiguration.java    License: 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 Project: eclair   Author: TinkoffCreditSystems   File: ExampleTest.java    License: 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 Project: eclair   Author: TinkoffCreditSystems   File: ExampleTest.java    License: 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 Project: eclair   Author: TinkoffCreditSystems   File: ExampleTableBuilder.java    License: 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 Project: cerebro   Author: voyages-sncf-technologies   File: LogWriter.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerInterceptor.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 #20
Source Project: edison-microservice   Author: otto-de   File: LoggersHtmlEndpoint.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: 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 Project: spring-cloud-cli   Author: spring-cloud   File: DeployerApplication.java    License: 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 Project: nacos-spring-boot-project   Author: nacos-group   File: PrintLogger.java    License: 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 #27
Source Project: pmq   Author: ppdaicorp   File: LogLevelConfig.java    License: 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 #28
Source Project: logger-spring-boot   Author: rozidan   File: LoggerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void isLogFatalEnabled() {
    LoggingSystem.get(ClassLoader.getSystemClassLoader())
            .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL);
    assertTrue(logger.isEnabled(LogLevel.FATAL, "logger name"));
}
 
Example #29
Source Project: magic-starter   Author: xkcoding   File: CustomLogModel.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
public CustomLogModel(LogLevel level) {
	super(LogType.CUSTOM, level);
}
 
Example #30
Source Project: logger-spring-boot   Author: rozidan   File: LoggerInterceptor.java    License: 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());
}