Java Code Examples for org.slf4j.Logger#info()

The following examples show how to use org.slf4j.Logger#info() . 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: ReflectionUtils.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Log the current thread stacks at INFO level.
 * @param log the logger that logs the stack trace
 * @param title a descriptive title for the call stacks
 * @param minInterval the minimum time from the last
 */
public static void logThreadInfo(Logger log,
                                 String title,
                                 long minInterval) {
  boolean dumpStack = false;
  if (log.isInfoEnabled()) {
    synchronized (ReflectionUtils.class) {
      long now = System.currentTimeMillis();
      if (now - previousLogTime >= minInterval * 1000) {
        previousLogTime = now;
        dumpStack = true;
      }
    }
    if (dumpStack) {
      try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        printThreadInfo(new PrintStream(buffer, false, "UTF-8"), title);
        log.info(buffer.toString(Charset.defaultCharset().name()));
      } catch (UnsupportedEncodingException ignored) {
        log.warn("Could not write thread info about '" + title +
            "' due to a string encoding issue.");
      }
    }
  }
}
 
Example 2
Source File: DynoJedisClient.java    From dyno with Apache License 2.0 6 votes vote down vote up
public DynoJedisClient build() {
    assert (appName != null);
    assert (clusterName != null);

    // Make sure that the user doesn't set isDatastoreClient and connectionPoolConsistency together.
    if (this.isDatastoreClient == true && this.connectionPoolConsistency != null) {
        throw new DynoException("Cannot set isDatastoreClient(true) and also set withConnectionPoolConsistency() together");
    }

    if (cpConfig == null) {
        cpConfig = new ArchaiusConnectionPoolConfiguration(appName);
        Logger.info("Dyno Client runtime properties: " + cpConfig.toString());
    }
    cpConfig.setConnectToDatastore(isDatastoreClient);

    // If a connection-pool level consistency setting was provided, add it here.
    if (this.connectionPoolConsistency != null) {
        cpConfig.setConnectionPoolConsistency(connectionPoolConsistency);
    }

    if (cpConfig.isDualWriteEnabled()) {
        return buildDynoDualWriterClient();
    } else {
        return buildDynoJedisClient();
    }
}
 
Example 3
Source File: Utils.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Issue a message to the log but only if the same message has not
 * been logged already in the same GATE session.
 * This is intended for explanations or warnings that should not be 
 * repeated every time the same situation occurs.
 * 
 * @param logger - the logger instance to use
 * @param level  - an SLF4J severity level for the message
 * @param message - the message itself
 */
public static void logOnce(Logger logger, Level level, String message) {
 if (!alreadyLoggedMessages.contains(message)) {
  switch (level) {
  	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:
  		// unknown log level, should be impossible
  }
  alreadyLoggedMessages.add(message);
 }
}
 
Example 4
Source File: UsageStatisticsManager.java    From deadcode4j with Apache License 2.0 6 votes vote down vote up
private void processResponse(HttpURLConnection urlConnection) throws IOException {
    final Logger logger = getLogger();
    int responseCode = urlConnection.getResponseCode();
    if (responseCode / 100 == 2) {
        logger.info("Usage statistics have been transferred.");
        return;
    }
    logger.info("Could not transfer usage statistics: {}/{}", responseCode, urlConnection.getResponseMessage());
    if (logger.isDebugEnabled()) {
        InputStream inputStream = urlConnection.getInputStream();
        try {
            List<String> response = IOUtils.readLines(inputStream, "UTF-8");
            for (String line : response) {
                logger.debug(line);
            }
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}
 
Example 5
Source File: AsmUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Check to see if a class is well-formed.
 *
 * @param logger the logger to write to if a problem is found
 * @param logTag a tag to print to the log if a problem is found
 * @param classNode the class to check
 * @return true if the class is ok, false otherwise
 */
public static boolean isClassOk(final Logger logger, final String logTag, final ClassNode classNode) {
  final StringWriter sw = new StringWriter();
  final ClassWriter verifyWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  classNode.accept(verifyWriter);
  final ClassReader ver = new ClassReader(verifyWriter.toByteArray());
  try {
    DrillCheckClassAdapter.verify(ver, false, new PrintWriter(sw));
  } catch(final Exception e) {
    logger.info("Caught exception verifying class:");
    logClass(logger, logTag, classNode);
    throw e;
  }
  final String output = sw.toString();
  if (!output.isEmpty()) {
    logger.info("Invalid class:\n" +  output);
    return false;
  }

  return true;
}
 
Example 6
Source File: LogHelper.java    From synapse with Apache License 2.0 5 votes vote down vote up
private static void log(final Logger logger, final LogLevel loglevel, final Map<String, Object> contexts, final String message, final Object[] msgParams, final Exception e) {
    putMDC(contexts);
    switch (loglevel) {
        case TRACE:
            if (logger.isTraceEnabled()) {
                logger.trace(message != null ? message : "", msgParams);
            }
            break;
        case DEBUG:
            if (logger.isDebugEnabled()) {
                logger.debug(message != null ? message : "", msgParams);
            }
            break;
        case INFO:
            logger.info(message != null ? message : "", msgParams);
            break;
        case WARN:
            logger.warn(message != null ? message : "", msgParams);
            break;
        case ERROR:
            logger.error(message != null ? message : "", msgParams, e);
            break;
        default:
            //Nicht möglich, wenn kein neuer Loglevel hinzugfügt wird.
            break;
    }
    removeMDC(contexts);
}
 
Example 7
Source File: FailFastUtil.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("MethodParameterNamingConvention")
static void failFastIfTimedOut(GitRepository repo, Logger logger, @Nullable ServiceRequestContext ctx,
                               String methodName, Object arg1, Object arg2, Object arg3) {
    if (ctx != null && ctx.isTimedOut()) {
        logger.info("{} Rejecting a request timed out already: repo={}/{}, method={}, args=[{}, {}, {}]",
                    ctx, repo.parent().name(), repo.name(), methodName, arg1, arg2, arg3);
        throw REQUEST_ALREADY_TIMED_OUT;
    }
}
 
Example 8
Source File: FilterServerUtil.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
public static void callShell(final String shellString, final Logger log) {
    Process process = null;
    try {
        String[] cmdArray = splitShellString(shellString);
        process = Runtime.getRuntime().exec(cmdArray);
        process.waitFor();
        log.info("CallShell: <{}> OK", shellString);
    } catch (Throwable e) {
        log.error("CallShell: readLine IOException, {}", shellString, e);
    } finally {
        if (null != process)
            process.destroy();
    }
}
 
Example 9
Source File: FIXMatrixUtil.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
static Message send(IActionContext actionContext,
		Message message) throws Exception {
	String serviceName = actionContext.getServiceName();
       IInitiatorService service = getClient(actionContext);

	boolean performance = false;
	if (service instanceof FIXClient) {
		performance = ((FIXClient)service).isPerformance();
	}

       Logger logger = actionContext.getLogger();

       if(!performance && logger.isInfoEnabled()) {
           logger.info("[{}] {}", serviceName, FixUtil.toString(message, FixUtil.getDictionary(message)));
       }

	if (message.getHeader().isSetField(MsgSeqNum.FIELD)) {
		int seqnum = message.getHeader().getInt(
				MsgSeqNum.FIELD);
		((FIXSession)service.getSession()).addExpectedSenderNum(seqnum);
	}

	Thread.sleep(actionContext.getTimeout());

	service.getSession().send(message);

       if(!performance && logger.isInfoEnabled()) {
           actionContext.getLogger().info("[{}] finished successfully\n", serviceName);
       }

	return message;
}
 
Example 10
Source File: LoggerSpaceFactory4Log4jBuilderTest.java    From sofa-common-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuild() {
    AbstractLoggerSpaceFactory loggerSpaceFactory = loggerSpaceFactory4Log4jBuilder.build(
        "com.alipay.sofa.rpc", this.getClass().getClassLoader());
    Logger logger = loggerSpaceFactory.getLogger("com.foo.Bar");

    logger.info("LoggerSpaceFactory4Log4jBuilderTest  pass.");

    logger = loggerSpaceFactory.getLogger("com.foo.Bar");

    Assert.assertNotNull(logger);
}
 
Example 11
Source File: Util.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
public static void toLog(Logger log, InputStream is) throws IOException {
	try (BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
		String curLine = null;
		while ((curLine = in.readLine()) != null) {
			log.info(curLine);
		}
	}
}
 
Example 12
Source File: MQHelper.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * Reset consumer topic offset according to time
 *
 * @param messageModel which model
 * @param instanceName which instance
 * @param consumerGroup consumer group
 * @param topic topic
 * @param timestamp time
 * @throws Exception
 */
public static void resetOffsetByTimestamp(
    final MessageModel messageModel,
    final String instanceName,
    final String consumerGroup,
    final String topic,
    final long timestamp) throws Exception {
    final Logger log = ClientLogger.getLog();

    DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(consumerGroup);
    consumer.setInstanceName(instanceName);
    consumer.setMessageModel(messageModel);
    consumer.start();

    Set<MessageQueue> mqs = null;
    try {
        mqs = consumer.fetchSubscribeMessageQueues(topic);
        if (mqs != null && !mqs.isEmpty()) {
            TreeSet<MessageQueue> mqsNew = new TreeSet<MessageQueue>(mqs);
            for (MessageQueue mq : mqsNew) {
                long offset = consumer.searchOffset(mq, timestamp);
                if (offset >= 0) {
                    consumer.updateConsumeOffset(mq, offset);
                    log.info("resetOffsetByTimestamp updateConsumeOffset success, {} {} {}",
                        consumerGroup, offset, mq);
                }
            }
        }
    } catch (Exception e) {
        log.warn("resetOffsetByTimestamp Exception", e);
        throw e;
    } finally {
        if (mqs != null) {
            consumer.getDefaultMQPullConsumerImpl().getOffsetStore().persistAll(mqs);
        }
        consumer.shutdown();
    }
}
 
Example 13
Source File: Help.java    From kite with Apache License 2.0 5 votes vote down vote up
private boolean printOption(Logger console, ParameterDescription param) {
  boolean required = param.getParameter().required();
  if (!param.getParameter().hidden()) {
    console.info("  {} {}\n\t{}{}", new Object[]{
        required ? "*" : " ",
        param.getNames().trim(),
        param.getDescription(),
        formatDefault(param)});
  }
  return required;
}
 
Example 14
Source File: Configuration.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public void logCommand(Logger log, String message) {
    if (printStream != null) {
        printStream.println(colored(COLOR_COMMAND, message));
    } else {
        log.info(message);
    }
}
 
Example 15
Source File: ArbitraryNameVersionDecision.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
@Override
public void printDescription(final Logger logger) {
    logger.info("Multiple unique detector types were found.");
    logger.info("The following project names were found: ");
    for (final DetectorProjectInfo projectNamePossibility : otherDetectors) {
        logger.info(projectNamePossibility.getDetectorType().toString() + ": " + projectNamePossibility.getNameVersion().getName());
    }
    logger.info("Chose to use " + chosenDetector.getDetectorType() + " at depth " + chosenDetector.getDepth() + " for project name and version.");
    logger.info("To specify a different detector type you can specify the project type override.");
}
 
Example 16
Source File: RetriableDataSource.java    From Patterdale with Apache License 2.0 5 votes vote down vote up
public static void logRetry(RuntimeParameters runtimeParams,
                            DatabaseDefinition databaseDefinition,
                            Logger logger) {
    logger.info(format("Attempting database connection to: %s at %s.%n" +
                    "Configured to retry %d times with a delay between retries of %d seconds.",
            databaseDefinition.name,
            databaseDefinition.jdbcUrl,
            runtimeParams.maxConnectionRetries(),
            runtimeParams.connectionRetryDelayInSeconds()));
}
 
Example 17
Source File: RemoteSolrServerProvider.java    From vind with Apache License 2.0 4 votes vote down vote up
@Override
public SolrClient getInstance() {

    Logger log = LoggerFactory.getLogger(SolrServerProvider.class);

    String host = SearchConfiguration.get(SearchConfiguration.SERVER_HOST);
    //Backwards compatibility
    String solrHost = SearchConfiguration.get(SearchConfiguration.SERVER_SOLR_HOST);
    if(host == null & solrHost != null) {
        host = solrHost;
    }

    if(host == null) {
        log.error("{} has to be set", SearchConfiguration.SERVER_HOST);
        throw new RuntimeException(SearchConfiguration.SERVER_HOST + " has to be set");
    }

    String collection = SearchConfiguration.get(SearchConfiguration.SERVER_COLLECTION);
    //Backwards compatibility
    String solrCollection = SearchConfiguration.get(SearchConfiguration.SERVER_SOLR_COLLECTION);
    if(collection == null & solrCollection != null) {
        collection = solrCollection;
    }

    final String connectionTimeout = SearchConfiguration.get(SearchConfiguration.SERVER_CONNECTION_TIMEOUT);
    final String soTimeout = SearchConfiguration.get(SearchConfiguration.SERVER_SO_TIMEOUT);

    if(SearchConfiguration.get(SearchConfiguration.SERVER_SOLR_CLOUD, false)) {
        log.info("Instantiating solr cloud client: {}", host);

        if(collection != null) {
            CloudSolrClient client = new CloudSolrClient.Builder(Arrays.asList(host), Optional.empty()).build();
            client.setDefaultCollection(collection);

            if(StringUtils.isNotEmpty(connectionTimeout)) {
                client.setZkConnectTimeout(Integer.valueOf(connectionTimeout));
            }

            if(StringUtils.isNotEmpty(soTimeout)) {
                client.setZkClientTimeout(Integer.valueOf(soTimeout));
            }

            return client;
        } else {
            log.error(SearchConfiguration.SERVER_COLLECTION + " has to be set");
            throw new RuntimeException(SearchConfiguration.SERVER_COLLECTION + " has to be set");
        }

    } else {

        if(collection != null) {
            host = String.join("/",host,collection);
        }
        log.info("Instantiating solr http client: {}", host);
        return new HttpSolrClient.Builder(host).build();

    }

}
 
Example 18
Source File: LogUtil.java    From Lottor with MIT License 4 votes vote down vote up
public static void info(Logger logger, Supplier<Object> supplier) {
    if (logger.isInfoEnabled()) {
        logger.info(Objects.toString(supplier.get()));
    }
}
 
Example 19
Source File: ScheduleTemplateImpl.java    From x7 with Apache License 2.0 4 votes vote down vote up
public boolean schedule(Class scheduleClazz, Callable<Boolean> callable) {

        Logger logger = LoggerFactory.getLogger(scheduleClazz);

        String loggingName = scheduleClazz.getSimpleName();

        boolean flag = false;
        long startTime = System.currentTimeMillis();
        String taskId = loggingName + "_" + startTime;

        logger.info("Executing " + loggingName + " At: " + new Date() + ", id: " + taskId);

        try {
            flag = callable.call();
        }catch (Exception e) {
            logger.info("Exception Occured: " + ExceptionUtil.getMessage(e));
        }

        long endTime = System.currentTimeMillis();

        String result = flag == true?"OK," :  "FAILED,";
        logger.info("Executing " + loggingName +", " + result +" Cost: " + (endTime - startTime) + "ms" + ", id: " + taskId);

        return flag;
    }
 
Example 20
Source File: LogUtil.java    From hmily with Apache License 2.0 2 votes vote down vote up
/**
 * Info.
 *
 * @param logger   the logger
 * @param supplier the supplier
 */
public static void info(Logger logger, Supplier<Object> supplier) {
    if (logger.isInfoEnabled()) {
        logger.info(Objects.toString(supplier.get()));
    }
}