Java Code Examples for org.apache.logging.log4j.Level#ERROR

The following examples show how to use org.apache.logging.log4j.Level#ERROR . 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: Log4J2Logger.java    From getty with Apache License 2.0 6 votes vote down vote up
private static Level toLevel(InternalLogLevel level) {
    switch (level) {
        case INFO:
            return Level.INFO;
        case DEBUG:
            return Level.DEBUG;
        case WARN:
            return Level.WARN;
        case ERROR:
            return Level.ERROR;
        case TRACE:
            return Level.TRACE;
        default:
            throw new Error();
    }
}
 
Example 2
Source File: SLF4JLogger.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Level getLevel() {
    if (logger.isTraceEnabled()) {
        return Level.TRACE;
    }
    if (logger.isDebugEnabled()) {
        return Level.DEBUG;
    }
    if (logger.isInfoEnabled()) {
        return Level.INFO;
    }
    if (logger.isWarnEnabled()) {
        return Level.WARN;
    }
    if (logger.isErrorEnabled()) {
        return Level.ERROR;
    }
    // Option: throw new IllegalStateException("Unknown SLF4JLevel");
    // Option: return Level.ALL;
    return Level.OFF;
}
 
Example 3
Source File: Log4J2Logger.java    From mynlp with Apache License 2.0 6 votes vote down vote up
protected Level toLevel(InternalLogLevel level) {
    switch (level) {
        case INFO:
            return Level.INFO;
        case DEBUG:
            return Level.DEBUG;
        case WARN:
            return Level.WARN;
        case ERROR:
            return Level.ERROR;
        case TRACE:
            return Level.TRACE;
        default:
            throw new Error();
    }
}
 
Example 4
Source File: LevelRangeFilter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a ThresholdFilter.
 *
 * @param minLevel
 *            The minimum log Level.
 * @param maxLevel
 *            The maximum log Level.
 * @param match
 *            The action to take on a match.
 * @param mismatch
 *            The action to take on a mismatch.
 * @return The created ThresholdFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static LevelRangeFilter createFilter(
        // @formatter:off
        @PluginAttribute final Level minLevel,
        @PluginAttribute final Level maxLevel,
        @PluginAttribute final Result match,
        @PluginAttribute final Result mismatch) {
        // @formatter:on
    final Level actualMinLevel = minLevel == null ? Level.ERROR : minLevel;
    final Level actualMaxLevel = maxLevel == null ? Level.ERROR : maxLevel;
    final Result onMatch = match == null ? Result.NEUTRAL : match;
    final Result onMismatch = mismatch == null ? Result.DENY : mismatch;
    return new LevelRangeFilter(actualMinLevel, actualMaxLevel, onMatch, onMismatch);
}
 
Example 5
Source File: RepositoryValidator.java    From fix-orchestra with Apache License 2.0 6 votes vote down vote up
/**
 * Validate an Orchestra repository file against the XML schema
 *
 * If the validation fails, an exception is thrown. If valid, there is no return.
 *
 * @throws ParserConfigurationException if the XML parser fails due to a configuration error
 * @throws SAXException if XML parser fails or the file is invalid
 * @throws IOException if the XML file cannot be read
 */
public void validate() throws IOException, ParserConfigurationException, SAXException {

  final Level level = verbose ? Level.DEBUG : Level.ERROR;
  if (logFile != null) {
    parentLogger = LogUtil.initializeFileLogger(logFile.getCanonicalPath(), level, getClass());
  } else {
    parentLogger = LogUtil.initializeDefaultLogger(level, getClass());
  }

  final ErrorListener errorHandler = new ErrorListener();
  final Document xmlDocument = validateSchema(errorHandler);
  validateExpressions(xmlDocument);

  if (getErrors() + getFatalErrors() > 0) {
    parentLogger.fatal("RepositoryValidator complete; fatal errors={} errors={} warnings={}",
        getFatalErrors(), getErrors(), getWarnings());
  } else {
    parentLogger.info("RepositoryValidator complete; fatal errors={} errors={} warnings={}",
        getFatalErrors(), getErrors(), getWarnings());
  }
}
 
Example 6
Source File: LogUtil.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private static Level getLog4jLevel(String level){
  if(level.equalsIgnoreCase("SEVERE")){
    return Level.ERROR;
  }
  else if(level.equalsIgnoreCase("WARNING")){
    return Level.WARN;
  }
  else if(level.equalsIgnoreCase("INFO")){
    return Level.INFO;
  }
  else if(level.equalsIgnoreCase("FINE")){
    return Level.DEBUG;
  }
  else if(level.equalsIgnoreCase("FINER") || level.equalsIgnoreCase("FINEST")){
    return Level.TRACE;
  }
  return Level.INFO;
}
 
Example 7
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig rootLoggerConfig = getRootLogger();
    rootLoggerConfig.addAppender(appender, null, null);

    final Level defaultLevel = Level.ERROR;
    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
            defaultLevel.name());
    final Level level = Level.valueOf(levelName);
    rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
 
Example 8
Source File: DynamicThresholdFilter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a DynamicThresholdFilter.
 * @param key The name of the key to compare.
 * @param pairs An array of value and Level pairs.
 * @param defaultThreshold The default Level.
 * @param onMatch The action to perform if a match occurs.
 * @param onMismatch The action to perform if no match occurs.
 * @return The DynamicThresholdFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static DynamicThresholdFilter createFilter(
        @PluginAttribute final String key,
        @PluginElement final KeyValuePair[] pairs,
        @PluginAttribute final Level defaultThreshold,
        @PluginAttribute final Result onMatch,
        @PluginAttribute final Result onMismatch) {
    final Map<String, Level> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        map.put(pair.getKey(), Level.toLevel(pair.getValue()));
    }
    final Level level = defaultThreshold == null ? Level.ERROR : defaultThreshold;
    return new DynamicThresholdFilter(key, map, level, onMatch, onMismatch);
}
 
Example 9
Source File: LoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@PluginFactory
public static LoggerConfig createLogger(
        // @formatter:off
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
        // @formatter:on
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);

    return new LoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, includeLocation(includeLocation, config));
}
 
Example 10
Source File: MyLogger.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void setLevel(Level level) {
	LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	Configuration config = ctx.getConfiguration();
	LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); 
	loggerConfig.setLevel(level);
	ctx.updateLoggers();
		if (level == Level.ERROR) {
			logger.error("<- This level is successfully initialized");
		}
		if (level == Level.WARN) {
			logger.warn("<- This level is successfully initialized");
		}
		if (level == Level.DEBUG) {
			logger.debug("<- This level is successfully initialized");
		}
		if (level == Level.INFO) {
			logger.info("<- This level is successfully initialized");
		}
}
 
Example 11
Source File: LevelMatchFilterBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Filter parseFilter(Element filterElement, XmlConfigurationFactory factory) {
    final Holder<String> level = new Holder<>();
    final Holder<Boolean> acceptOnMatch = new BooleanHolder();
    forEachElement(filterElement.getElementsByTagName("param"), (currentElement) -> {
        if (currentElement.getTagName().equals("param")) {
            switch (currentElement.getAttribute(NAME_ATTR).toLowerCase()) {
                case LEVEL:
                    level.set(currentElement.getAttribute(VALUE_ATTR));
                    break;
                case ACCEPT_ON_MATCH:
                    acceptOnMatch.set(Boolean.parseBoolean(currentElement.getAttribute(VALUE_ATTR)));
                    break;
            }
        }
    });
    Level lvl = Level.ERROR;
    if (level.get() != null) {
        lvl = Level.toLevel(level.get(), Level.ERROR);
    }
    org.apache.logging.log4j.core.Filter.Result onMatch = acceptOnMatch.get() != null && acceptOnMatch.get()
            ? org.apache.logging.log4j.core.Filter.Result.ACCEPT
            : org.apache.logging.log4j.core.Filter.Result.DENY;
    return new FilterWrapper(LevelMatchFilter.newBuilder()
            .setLevel(lvl)
            .setOnMatch(onMatch)
            .setOnMismatch(org.apache.logging.log4j.core.Filter.Result.NEUTRAL)
            .build());
}
 
Example 12
Source File: LevelMatchFilterBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Filter createFilter(String level, boolean acceptOnMatch) {
    Level lvl = Level.ERROR;
    if (level != null) {
        lvl = Level.toLevel(level, Level.ERROR);
    }
    org.apache.logging.log4j.core.Filter.Result onMatch = acceptOnMatch
            ? org.apache.logging.log4j.core.Filter.Result.ACCEPT
            : org.apache.logging.log4j.core.Filter.Result.DENY;
    return new FilterWrapper(LevelMatchFilter.newBuilder()
            .setLevel(lvl)
            .setOnMatch(onMatch)
            .setOnMismatch(org.apache.logging.log4j.core.Filter.Result.NEUTRAL)
            .build());
}
 
Example 13
Source File: LoggerConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 */
public LoggerConfig() {
    this.logEventFactory = LOG_EVENT_FACTORY;
    this.level = Level.ERROR;
    this.name = Strings.EMPTY;
    this.properties = null;
    this.propertiesRequireLookup = false;
    this.config = null;
    this.reliabilityStrategy = new DefaultReliabilityStrategy(this);
}
 
Example 14
Source File: StatusConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Specifies the logging level by name to use for filtering StatusLogger messages.
 *
 * @param status name of logger level to filter below.
 * @return {@code this}
 * @see Level
 */
public StatusConfiguration setStatus(final String status) {
    this.status = Level.toLevel(status, null);
    if (this.status == null) {
        this.error("Invalid status level specified: " + status + ". Defaulting to ERROR.");
        this.status = Level.ERROR;
    }
    return this;
}
 
Example 15
Source File: TextAreaAppender.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
/**
  * This method is where the appender does the work.
  *
  * @param event Log event with log data
  */
 @Override
 public void append(LogEvent event) {
   readLock.lock();
   String message = new String(getLayout().toByteArray(event));
   Level l = event.getLevel();
if (styledText!=null) {
	StyleRange styleRange = new StyleRange();
	if (l==Level.ERROR) {
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cred;
		
	}
	else if (l==Level.WARN) {
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cblue;
	}
	else {
		
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cblack;
	}
	Display.getDefault().asyncExec(new Runnable() {
		public void run() {
			// Append formatted message to textarea.
			styleRange.start = styledText.getCharCount();
			styledText.append(message);
			styledText.setStyleRange(styleRange);
			styledText.setSelection(styledText.getCharCount());
		}
	});
}
readLock.unlock();
 }
 
Example 16
Source File: UtilsUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test setting the global logging level for Picard, Log4j, MinLog and java.util.logging.
 *
 * Note that there are three very similar, but not identical, logging level enums from different namespaces
 * being used here. The one used by Picard (and Hellbender --verbosity) of type "Log.LogLevel", the parallel
 * one used by log4j of type "Level", and the one used by java.utils.logging.
 *
 */
@Test
public void testSetLoggingLevel() {
    // Query and cache the initial  Log4j level in place at the start of the tests so we can restore it at the
    // end of the tests. Also, since we're QUERYING the Log4j level, but we're SETTING the level using the
    // LoggingUtils API, we also need to verify here that the initial level is one of the narrower set of levels
    // that is supported by LoggingUtils, since those are the only ones we can restore through the LoggingUtils API.
    Level initialLevel = logger.getLevel();
    boolean goodInitialLevel =
            initialLevel == Level.DEBUG ||
            initialLevel == Level.WARN ||
            initialLevel == Level.ERROR ||
            initialLevel == Level.INFO;
    Assert.assertTrue(goodInitialLevel);

    // Set and test each supported logging level in turn
    LoggingUtils.setLoggingLevel(LogLevel.DEBUG);
    Assert.assertTrue(logger.getLevel() == Level.DEBUG);

    LoggingUtils.setLoggingLevel(LogLevel.WARNING);
    Assert.assertTrue(logger.getLevel() == Level.WARN);

    LoggingUtils.setLoggingLevel(LogLevel.ERROR);
    Assert.assertTrue(logger.getLevel() == Level.ERROR);

    LoggingUtils.setLoggingLevel(LogLevel.INFO);
    Assert.assertTrue(logger.getLevel() == Level.INFO);

    // Restore the logging level back to the original level in place at the beginning of the test
    LoggingUtils.setLoggingLevel(LoggingUtils.levelFromLog4jLevel(initialLevel));
    Assert.assertTrue(logger.getLevel() == initialLevel);
}
 
Example 17
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected Level getDefaultStatus() {
    final String statusLevel = PropertiesUtil.getProperties().getStringProperty(
            Constants.LOG4J_DEFAULT_STATUS_LEVEL, Level.ERROR.name());
    try {
        return Level.toLevel(statusLevel);
    } catch (final Exception ex) {
        return Level.ERROR;
    }
}
 
Example 18
Source File: ThresholdFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ThresholdFilter.
 * @param level The log Level.
 * @param match The action to take on a match.
 * @param mismatch The action to take on a mismatch.
 * @return The created ThresholdFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static ThresholdFilter createFilter(
        @PluginAttribute final Level level,
        @PluginAttribute("onMatch") final Result match,
        @PluginAttribute("onMismatch") final Result mismatch) {
    final Level actualLevel = level == null ? Level.ERROR : level;
    final Result onMatch = match == null ? Result.NEUTRAL : match;
    final Result onMismatch = mismatch == null ? Result.DENY : mismatch;
    return new ThresholdFilter(actualLevel, onMatch, onMismatch);
}
 
Example 19
Source File: DiscardingAsyncQueueFullPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRouteEnqueuesIfThresholdCapacityReachedButLevelMoreSpecificThanThreshold()
        throws Exception {
    final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

    for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) {
        assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level));
        assertEquals(level.name(), EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level));
        assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level));
        assertEquals(level.name(), EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level));
    }
}
 
Example 20
Source File: LoggingConfigurator.java    From teku with Apache License 2.0 5 votes vote down vote up
private static LoggerConfig setUpValidatorLogger(final Appender appender) {
  // Don't disable validator error logs unless the root log level disables error.
  final Level validatorLogLevel =
      INCLUDE_VALIDATOR_DUTIES || ROOT_LOG_LEVEL.isMoreSpecificThan(Level.ERROR)
          ? ROOT_LOG_LEVEL
          : Level.ERROR;
  final LoggerConfig logger = new LoggerConfig(VALIDATOR_LOGGER_NAME, validatorLogLevel, true);
  logger.addAppender(appender, ROOT_LOG_LEVEL, null);
  return logger;
}