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

The following examples show how to use org.apache.logging.log4j.Level#DEBUG . 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: S1Command.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
private S1Packet writeCommand(int command, byte data[], boolean ongoing) throws X10FlashException, IOException {
	S1Packet reply=null;
	if (!_simulate) {
			if (MyLogger.getLevel()==Level.DEBUG) {
				try {
					Thread.sleep(125);
				}catch (Exception e) {}
			}
 		S1Packet p = new S1Packet(command,data,ongoing);
 		try {
  		reply =  USBFlash.writeS1(p);
 		}
 		catch (X10FlashException xe) {
 			xe.printStackTrace();
 			p.release();
 			throw new X10FlashException(xe.getMessage());
 		}
 		catch (IOException ioe) {
 			ioe.printStackTrace();
 			p.release();
 			throw new IOException(ioe.getMessage());
 		}
 }
	return reply;
}
 
Example 2
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 3
Source File: LogTypeConverter.java    From teku with Apache License 2.0 6 votes vote down vote up
@Override
public Level convert(String value) {
  switch (value.toUpperCase()) {
    case "OFF":
      return Level.OFF;
    case "FATAL":
      return Level.FATAL;
    case "WARN":
      return Level.WARN;
    case "INFO":
      return Level.INFO;
    case "DEBUG":
      return Level.DEBUG;
    case "TRACE":
      return Level.TRACE;
    case "ALL":
      return Level.ALL;
  }
  throw (new CommandLine.TypeConversionException(
      "'"
          + value
          + "' is not a valid log level. Supported values are [OFF|FATAL|WARN|INFO|DEBUG|TRACE|ALL]"));
}
 
Example 4
Source File: Log4j2LoggerSpaceFactory.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
private Level toLog4j2Level(AdapterLevel adapterLevel) {
    if (adapterLevel == null) {
        throw new IllegalStateException("AdapterLevel is NULL when adapter to log4j2.");
    }
    switch (adapterLevel) {
        case TRACE:
            return Level.TRACE;
        case DEBUG:
            return Level.DEBUG;
        case INFO:
            return Level.INFO;
        case WARN:
            return Level.WARN;
        case ERROR:
            return Level.ERROR;
        default:
            throw new IllegalStateException(adapterLevel
                                            + " is unknown when adapter to log4j2.");
    }
}
 
Example 5
Source File: Log4j2AppenderComparisonBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(MESSAGE);
    final Throwable t = null;
    final StringMap mdc = null;
    final ThreadContext.ContextStack ndc = null;
    final String threadName = "THREAD";
    final StackTraceElement location = null;
    final long timestamp = System.currentTimeMillis();

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example 6
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 7
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 8
Source File: TextEncoderHelperBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example 9
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 10
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 11
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 12
Source File: MessageRouter.java    From Mixin with MIT License 5 votes vote down vote up
private static Level messageKindToLoggingLevel(Kind kind) {
    switch (kind) {
        case ERROR:
            return Level.ERROR;
        case WARNING:
        case MANDATORY_WARNING:
            return Level.WARN;
        case NOTE:
            return Level.INFO;
        case OTHER:
        default:
            return Level.DEBUG;
    }
}
 
Example 13
Source File: BasicConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public BasicConfiguration(final LoggerContext loggerContext) {
    super(loggerContext, ConfigurationSource.NULL_SOURCE);

    final LoggerConfig root = getRootLogger();
    setName("BasicConfiguration");
    final String levelName = System.getProperty(DEFAULT_LEVEL);
    final Level level = (levelName != null && Level.getLevel(levelName) != null) ? Level.getLevel(levelName)
            : Level.DEBUG;
    root.setLevel(level);
}
 
Example 14
Source File: JoinHelper.java    From crate with Apache License 2.0 5 votes vote down vote up
static Level getLogLevel(TransportException e) {
    Throwable cause = e.unwrapCause();
    if (cause instanceof CoordinationStateRejectedException ||
        cause instanceof FailedToCommitClusterStateException ||
        cause instanceof NotMasterException) {
        return Level.DEBUG;
    }
    return Level.INFO;
}
 
Example 15
Source File: DiscardingAsyncQueueFullPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRouteDiscardsIfThresholdCapacityReachedAndLevelEqualOrLessSpecificThanThreshold()
        throws Exception {
    final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN);

    for (final Level level : new Level[] {Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL}) {
        assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level));
        assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level));
        assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level));
        assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level));
    }
}
 
Example 16
Source File: Log4J2Logger.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setLevel(@Nonnull LoggerLevel level) throws IllegalAccessException {
  Class callerClass = ReflectionUtil.findCallerClass(1);
  if (callerClass == null) {
    throw new IllegalAccessException("There not caller class");
  }

  PluginDescriptor plugin = PluginManager.getPlugin(callerClass);
  if (plugin == null || !PluginIds.isPlatformPlugin(plugin.getPluginId())) {
    throw new IllegalAccessException("Plugin is not platform: " + plugin);
  }

  org.apache.logging.log4j.core.Logger logger = myLoggerContext.getLogger(myLogger.getName());

  Level newLevel;
  switch (level) {

    case INFO:
      newLevel = Level.INFO;
      break;
    case WARNING:
      newLevel = Level.WARN;
      break;
    case ERROR:
      newLevel = Level.ERROR;
      break;
    case DEBUG:
      newLevel = Level.DEBUG;
      break;
    case TRACE:
      newLevel = Level.TRACE;
      break;
    default:
      throw new IllegalArgumentException("Wrong level: " + level);
  }

  logger.setLevel(newLevel);
}
 
Example 17
Source File: EthSignerTestHarnessFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
public static EthSignerTestHarness create(
    final Path tempDir, final String keyPath, final Integer besuPort, final long chainId)
    throws IOException, CipherException {

  final Path keyFilePath = copyResource(keyPath, tempDir.resolve(keyPath));

  final EthSignerConfig config =
      new EthSignerConfig(
          Level.DEBUG,
          HOST,
          besuPort,
          Duration.ofSeconds(10),
          HOST,
          0,
          new ConfigurationChainId(chainId),
          tempDir);

  final EthSigner ethSigner =
      new EthSigner(
          config,
          new SingleTransactionSignerProvider(
              new CredentialTransactionSigner(
                  WalletUtils.loadCredentials("", keyFilePath.toAbsolutePath().toFile()))));
  ethSigner.run();

  waitForPortFile(tempDir);

  LOG.info("EthSigner port: {}", config.getHttpListenPort());

  return new EthSignerTestHarness(config, loadPortsFile(tempDir));
}
 
Example 18
Source File: MixinProcessor.java    From Mixin with MIT License 5 votes vote down vote up
private void select(MixinEnvironment environment) {
    this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG;
    if (this.transformedCount > 0) {
        MixinProcessor.logger.log(this.verboseLoggingLevel, "Ending {}, applied {} mixins", this.currentEnvironment, this.transformedCount);
    }
    String action = this.currentEnvironment == environment ? "Checking for additional" : "Preparing";
    MixinProcessor.logger.log(this.verboseLoggingLevel, "{} mixins for {}", action, environment);
    
    this.profiler.setActive(true);
    this.profiler.mark(environment.getPhase().toString() + ":prepare");
    Section prepareTimer = this.profiler.begin("prepare");
    
    this.selectConfigs(environment);
    this.extensions.select(environment);
    int totalMixins = this.prepareConfigs(environment);
    this.currentEnvironment = environment;
    this.transformedCount = 0;

    prepareTimer.end();
    
    long elapsedMs = prepareTimer.getTime();
    double elapsedTime = prepareTimer.getSeconds();
    if (elapsedTime > 0.25D) {
        long loadTime = this.profiler.get("class.load").getTime();
        long transformTime = this.profiler.get("class.transform").getTime();
        long pluginTime = this.profiler.get("mixin.plugin").getTime();
        String elapsed = new DecimalFormat("###0.000").format(elapsedTime);
        String perMixinTime = new DecimalFormat("###0.0").format(((double)elapsedMs) / totalMixins);
        
        MixinProcessor.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({}ms avg) ({}ms load, {}ms transform, {}ms plugin)",
                totalMixins, elapsed, perMixinTime, loadTime, transformTime, pluginTime);
    }

    this.profiler.mark(environment.getPhase().toString() + ":apply");
    this.profiler.setActive(environment.getOption(Option.DEBUG_PROFILER));
}
 
Example 19
Source File: RepositoryCompressor.java    From fix-orchestra with Apache License 2.0 4 votes vote down vote up
private void compress(InputStream is, OutputStream os,
    Predicate<? super MessageType> messagePredicate) throws JAXBException, IOException {

  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 Repository inRepository = unmarshal(is);
  isCategoryInSection.setCategories(inRepository.getCategories().getCategory());
  final Repository outRepository = new Repository();
  inRepository.copyTo(null, outRepository, AttributeCopyStrategy.INSTANCE);

  final ElementOrRefinementContainer metadata =
      (ElementOrRefinementContainer) inRepository.getMetadata().clone();
  final List<JAXBElement<SimpleLiteral>> literals = metadata.getAny();
  final ObjectFactory objectFactory = new ObjectFactory();
  final SimpleLiteral contributor = new SimpleLiteral();
  contributor.getContent().add("RepositoryCompressor");
  literals.add(objectFactory.createContributor(contributor));
  outRepository.setMetadata(metadata);
  outRepository.setCategories((Categories) inRepository.getCategories().clone());
  outRepository.setSections((Sections) inRepository.getSections().clone());
  outRepository.setDatatypes((Datatypes) inRepository.getDatatypes().clone());
  final Actors actors = inRepository.getActors();
  if (actors != null) {
    outRepository.setActors((Actors) actors.clone());
  }
  final Components components = inRepository.getComponents();
  if (components != null) {
    final Components inComponents = (Components) components.clone();
    componentList = inComponents.getComponent();
  }
  final Groups inGroups = (Groups) inRepository.getGroups().clone();
  groupList = inGroups.getGroup();

  final Messages inMessages = (Messages) inRepository.getMessages().clone();
  final List<MessageType> messageList = inMessages.getMessage();
  final List<MessageType> filteredMessages =
      messageList.stream().filter(messagePredicate).collect(Collectors.toList());
  filteredMessages.forEach(m -> walk(m.getStructure().getComponentRefOrGroupRefOrFieldRef()));

  final List<BigInteger> distinctFieldIds =
      fieldIdList.stream().distinct().collect(Collectors.toList());
  final Fields inFields = (Fields) inRepository.getFields().clone();
  final List<FieldType> fieldsWithFlow = inFields.getField().stream()
      .filter(f -> distinctFieldIds.contains(f.getId())).collect(Collectors.toList());
  final Fields outFields = new Fields();
  outFields.getField().addAll(fieldsWithFlow);
  outRepository.setFields(outFields);

  final List<String> typeList =
      fieldsWithFlow.stream().map(FieldType::getType).distinct().collect(Collectors.toList());
  final CodeSets inCodeSets = (CodeSets) inRepository.getCodeSets().clone();
  final List<CodeSetType> codeSetsWithFlow = inCodeSets.getCodeSet().stream()
      .filter(cs -> typeList.contains(cs.getName())).collect(Collectors.toList());
  final CodeSets outCodeSets = new CodeSets();
  outCodeSets.getCodeSet().addAll(codeSetsWithFlow);
  outRepository.setCodeSets(outCodeSets);

  final List<BigInteger> distinctComponentsIds =
      componentIdList.stream().distinct().collect(Collectors.toList());
  final List<ComponentType> componentsWithFlow = componentList.stream()
      .filter(c -> distinctComponentsIds.contains(c.getId())).collect(Collectors.toList());
  final Components outComponents = new Components();
  outComponents.getComponent().addAll(componentsWithFlow);
  outRepository.setComponents(outComponents);

  final List<BigInteger> distinctGroupIds =
      groupIdList.stream().distinct().collect(Collectors.toList());
  final List<GroupType> groupWithFlow = groupList.stream()
      .filter(c -> distinctGroupIds.contains(c.getId())).collect(Collectors.toList());
  final Groups outGroups = new Groups();
  outGroups.getGroup().addAll(groupWithFlow);
  outRepository.setGroups(outGroups);

  final Messages outMessages = new Messages();
  outMessages.getMessage().addAll(filteredMessages);
  outRepository.setMessages(outMessages);
  marshal(outRepository, os);
}
 
Example 20
Source File: LevelTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testLevelLogging() {
    final Marker marker = MarkerManager.getMarker("marker");
    final Message msg = new ObjectMessage("msg");
    final Throwable t = new Throwable("test");
    final Level[] levels = new Level[] { Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL };
    final String[] names = new String[] { "levelTest", "levelTest.Trace", "levelTest.Debug", "levelTest.Info",
            "levelTest.Warn", "levelTest.Error", "levelTest.Fatal" };
    for (final Level level : levels) {
        for (final String name : names) {
            final Logger logger = context.getLogger(name);
            logger.log(level, msg); // Message
            logger.log(level, 123); // Object
            logger.log(level, name); // String
            logger.log(level, marker, msg); // Marker, Message
            logger.log(level, marker, 123); // Marker, Object
            logger.log(level, marker, name); // marker, String
            logger.log(level, msg, t); // Message, Throwable
            logger.log(level, 123, t); // Object, Throwable
            logger.log(level, name, "param1", "param2"); // String, Object...
            logger.log(level, name, t); // String, Throwable
            logger.log(level, marker, msg, t); // Marker, Message, Throwable
            logger.log(level, marker, 123, t); // Marker, Object, Throwable
            logger.log(level, marker, name, "param1", "param2"); // Marker, String, Object...
            logger.log(level, marker, name, t); // Marker, String, Throwable
        }
    }
    // Logger "levelTest" will not receive same events as "levelTest.Trace"
    int levelCount = names.length - 1;

    final int UNIT = 14;
    final Expected[] expectedResults = new Expected[] { //
    new Expected(listAll, UNIT * levelCount, "TRACE", "All"), //
            new Expected(listTrace, UNIT * levelCount--, "TRACE", "Trace"), //
            new Expected(listDebug, UNIT * levelCount--, "DEBUG", "Debug"), //
            new Expected(listInfo, UNIT * levelCount--, "INFO", "Info"), //
            new Expected(listWarn, UNIT * levelCount--, "WARN", "Warn"), //
            new Expected(listError, UNIT * levelCount--, "ERROR", "Error"), //
            new Expected(listFatal, UNIT * levelCount--, "FATAL", "Fatal"), //
    };
    for (final Expected expected : expectedResults) {
        final String description = expected.description;
        final List<LogEvent> events = expected.appender.getEvents();
        assertNotNull(description + ": No events", events);
        assertThat(events, hasSize(expected.expectedEventCount));
        final LogEvent event = events.get(0);
        assertEquals(
            description + ": Expected level " + expected.expectedInitialEventLevel + ", got" + event.getLevel(),
            event.getLevel().name(), expected.expectedInitialEventLevel);
    }
}