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

The following are Jave code examples for showing how to use info() of the org.slf4j.Logger class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: otter-G   File: LogInterceptor.java   View Source Code Vote up 6 votes
/**
 * 记录请求信息
 * 
 * @param methodInvocation
 * @param take
 */
private void dump(MethodInvocation methodInvocation, Object result, long take) {
    // 取得日志打印对象
    Logger log = getLogger(methodInvocation.getMethod().getDeclaringClass());
    Object[] args = methodInvocation.getArguments();
    StringBuffer buffer = getArgsString(args);

    if (log.isInfoEnabled()) {
        String className = ClassUtils.getShortClassName(methodInvocation.getMethod().getDeclaringClass());
        String methodName = methodInvocation.getMethod().getName();
        String resultStr = getResultString(result);

        String now = new SimpleDateFormat(DATA_FORMAT).format(new Date());
        log.info(MessageFormat.format(MESSAGE, new Object[] { className, methodName, now, take, buffer.toString(),
                resultStr }));
    }
}
 
Example 2
Project: QDrill   File: AsmUtil.java   View Source Code Vote up 6 votes
/**
 * 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 3
Project: openNaEF   File: CommandUtil.java   View Source Code Vote up 6 votes
public static void logCommands(List<String> commands) {
    Logger log = LoggerFactory.getLogger(CommandUtil.class);
    log.info("commands ----");
    String formatter = "%0" + String.valueOf(commands.size()).length() + "d";
    int line = 0;
    for (String command : commands) {
        line++;
        if (command == null) {
            command = "";
        } else if (command.contains("パスワード")) {
            command = escape(command, "パスワード");
        } else if (command.toLowerCase().contains("password")) {
            command = escape(command, "password");
        }
        log.info("[" + String.format(formatter, Integer.valueOf(line)) + "] " + command);
    }
    log.info("----");
}
 
Example 4
Project: afp-api-client   File: GetSomeAFPData.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
	Logger logger = LoggerFactory.getLogger(GetSomeAFPData.class);

	Proxy proxy = null;
	// If you are behind a proxy, use the following line with the correct parameters :
	// proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("firewall.company.com", 80));

	Map<String, String> authentication = null;
	// If you want to use your credentials on api.afp.com, provide the following informations :
	// authentication = new HashMap<String, String>();
	// authentication.put(AFPAuthenticationManager.KEY_CLIENT, "client");
	// authentication.put(AFPAuthenticationManager.KEY_SECRET, "secret");
	// authentication.put(AFPAuthenticationManager.KEY_USERNAME, "username");
	// authentication.put(AFPAuthenticationManager.KEY_PASSWORD, "password");

	AFPDataGrabber afp = new AFPDataGrabber(LangEnum.EN, authentication, logger, dataDir,
			AFPDataGrabberCache.noCache(), proxy);

	AFPGrabSession gs = afp.grabSearchMax(false, 10);
	logger.info("Grabbed " + gs.getAllDocuments().size() + " documents as [" + gs.getAuthenticatedAs() + "] in "
			+ gs.getDir());
	for (FullNewsDocument nd : gs.getAllDocuments()) {
		logger.info("    - " + nd.getUno() + " : " + nd.getFullTitle());
	}
}
 
Example 5
Project: TOSCAna   File: NodeStack.java   View Source Code Vote up 6 votes
public void buildToDockerfile(TransformationContext context, BaseImageMapper mapper) throws IOException {
    Logger logger = context.getLogger(NodeStack.class);
    ImageMappingVisitor mappingVisitor = new ImageMappingVisitor(mapper);
    for (int i = stackNodes.size() - 1; i >= 0; i--) {
        KubernetesNodeContainer c = stackNodes.get(i);
        c.getNode().accept(mappingVisitor);
    }

    if (!mappingVisitor.getBaseImage().isPresent()) {
        throw new UnsupportedOperationException("Transformation of the Stack " + this + " is not possible!");
    }
    String baseImage = mappingVisitor.getBaseImage().get();
    logger.info("Determined Base Image {} for stack {}", baseImage, this);

    DockerfileBuildingVisitor visitor = new DockerfileBuildingVisitor(baseImage, this, context);
    visitor.buildAndWriteDockerfile();
    this.openPorts.addAll(visitor.getPorts());
    dockerfilePath = "output/docker/" + getStackName();
}
 
Example 6
Project: rmq4note   File: MQHelper.java   View Source Code Vote up 5 votes
/**
 * 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 7
Project: sagiri   File: ShutdownHook.java   View Source Code Vote up 5 votes
public void run() {
    Logger logger = LoggerFactory.getLogger(getClass());
    logger.info("Executing shutdown hook.");

    logger.info("Stopping plugins.");
    for(PluginBubble bubble : Sagiri.getPlugins()) {
        bubble.getPlugin().stop();
        logger.info(String.format("Stopped plugin: %s", bubble.getName()));
    }
}
 
Example 8
Project: Telebot   File: Telebot.java   View Source Code Vote up 5 votes
/**
 * Gets update observable.
 *
 * @return the update observable
 */
public static Observable<IUpdate> getUpdateObservable() {
    if (UpdateObservable == null) {
        Logger.info("Update Observable wasn't created yet, creating now...");
        createObservable();
    }
    return UpdateObservable;
}
 
Example 9
Project: mzzb-server   File: AutoRunConfig.java   View Source Code Vote up 5 votes
private void fetchAmazonDiscsData(int retry) {
    Logger logger = LoggerFactory.getLogger(AutoRunConfig.class);
    if (retry == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("fetching amazon discs data failed");
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("fetching amazon discs data ({})", retry);
        }
        try {
            amazonDiscsSpider.fetch();
        } catch (IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("fetching amazon discs data throw an error", e);
            }
            if (retry > 0) {
                fetchSakuraSpeedData(retry - 1);
            } else {
                return;
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("fetched amazon discs data ({})", retry);
        }
    }
}
 
Example 10
Project: cerebro   File: LogWriter.java   View Source Code Vote up 5 votes
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 11
Project: flywheel   File: Launchpad.java   View Source Code Vote up 5 votes
Launchpad(File profilePath) throws LaunchpadException {
  if (! profilePath.exists()) {
    throw new LaunchpadException("Profile path " + profilePath + " does not exist", null);
  }
  
  if (! profilePath.isDirectory()) {
    throw new LaunchpadException("Profile path must be a directory", null);
  }
  
  final File profileYaml = new File(profilePath.getPath() + "/profile.yaml");
  if (! profileYaml.exists()) {
    throw new LaunchpadException("Profile configuration " + profileYaml + " is missing", null);
  }

  profile = rethrowLaunchpadException(() -> {
    return Profile.fromFile(profileYaml);
  }, "Error reading profile");
  
  final StringBuilder sb = new StringBuilder();
  
  rethrowLaunchpadException(() -> {
    sb.append("\n  Flywheel version: ").append(FlywheelVersion.get());
    sb.append("\n  Indigo version: ").append(IndigoVersion.get());
  }, "Error retrieving version"); 
  
  sb.append("\n  Properties:");
  for (Map.Entry<String, ?> entry : profile.properties.entrySet()) {
    sb.append("\n    ").append(entry.getKey()).append(": ").append(entry.getValue());
  }
  
  sb.append("\n  Launchers:");
  for (Launcher launcher : profile.launchers) {
    sb.append("\n    ").append(launcher);
  }
  
  final Logger log = LoggerFactory.getLogger(Launchpad.class);
  log.info(sb.toString());
}
 
Example 12
Project: ServiceServer   File: LogUtil.java   View Source Code Vote up 5 votes
/**
 * Print logs of http request.
 */
public static void logReq(Logger logger, HttpServletRequest req) {
    String queryStr = req.getQueryString();
    if (queryStr == null || queryStr.length() == 0) {
        logger.info(req.getMethod() + " " + req.getRequestURI());
    } else {
        try {
            queryStr = URLDecoder.decode(queryStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn(e.getMessage());
        }
        logger.info(req.getMethod() + " " + req.getRequestURI() + "?" + queryStr);
    }
}
 
Example 13
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MixAll.java   View Source Code Vote up 5 votes
public static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (log != null) {
                    log.info(name + "=" + value);
                }
            }
        }
    }
}
 
Example 14
Project: QDrill   File: UserException.java   View Source Code Vote up 5 votes
/**
 * builds a user exception or returns the wrapped one. If the error is a system error, the error message is logged
 * to the given {@link Logger}.
 *
 * @param logger the logger to write to
 * @return user exception
 */
public UserException build(final Logger logger) {
  if (uex != null) {
    return uex;
  }

  boolean isSystemError = errorType == DrillPBError.ErrorType.SYSTEM;

  // make sure system errors use the root error message and display the root cause class name
  if (isSystemError) {
    message = ErrorHelper.getRootMessage(cause);
  }

  final UserException newException = new UserException(this);

  // since we just created a new exception, we should log it for later reference. If this is a system error, this is
  // an issue that the Drill admin should pay attention to and we should log as ERROR. However, if this is a user
  // mistake or data read issue, the system admin should not be concerned about these and thus we'll log this
  // as an INFO message.
  if (isSystemError) {
    logger.error(newException.getMessage(), newException);
  } else {
    logger.info("User Error Occurred", newException);
  }

  return newException;
}
 
Example 15
Project: FSTestTools   File: LogTestMethodNameRule.java   View Source Code Vote up 4 votes
@Override
protected void starting(Description description) {
    final Logger logger = LoggerFactory.getLogger(description.getTestClass());
    logger.info("Start of '{}'...", description.getMethodName());
}
 
Example 16
Project: logback-logdna   File: LogDNATest.java   View Source Code Vote up 4 votes
/**
 * 
 * Signup for LogDNA then run the test like this to try it out.
 * 
 *    mvn test -DLOGDNA_INGEST_KEY="<my_logdna_ingest_key"
 */
@Test
public void testLogDNALogbackConf() throws InterruptedException
{
	MDC.put("customerId", "C-1");
	MDC.put("requestId", "cafebabe1");
	
    Logger logger = LoggerFactory.getLogger(LogDNATest.class);

    logger.info("Okay");
    
    logger.warn("Hmmm, that seemed odd...");
    
    logger.error("Ah Sh*t!", new RuntimeException("Bang!"));
    
    logger.info("Well, Bye!");
    
    Thread.sleep(2000);
}
 
Example 17
Project: happylifeplat-tcc   File: LogUtil.java   View Source Code Vote up 4 votes
public static void info(Logger logger, String format, Supplier<Object> supplier) {
    if (logger.isInfoEnabled()) {
        logger.info(format, supplier.get());
    }
}
 
Example 18
Project: fuck_zookeeper   File: Environment.java   View Source Code Vote up 4 votes
public static void logEnv(String msg, Logger log) {
    List<Entry> env = Environment.list();
    for (Entry e : env) {
        log.info(msg + e.toString());
    }
}
 
Example 19
Project: incubator-ratis   File: RaftBasicTests.java   View Source Code Vote up 4 votes
static void runTestBasicAppendEntries(
    boolean async, int numMessages, MiniRaftCluster cluster, Logger LOG) throws Exception {
  LOG.info("runTestBasicAppendEntries: async? " + async + ", numMessages=" + numMessages);
  RaftServerImpl leader = waitForLeader(cluster);
  final long term = leader.getState().getCurrentTerm();
  final RaftPeerId killed = cluster.getFollowers().get(0).getId();
  cluster.killServer(killed);
  LOG.info(cluster.printServers());

  final SimpleMessage[] messages = SimpleMessage.create(numMessages);

  try (final RaftClient client = cluster.createClient()) {
    final AtomicInteger asyncReplyCount = new AtomicInteger();
    final CompletableFuture<Void> f = new CompletableFuture<>();

    for (SimpleMessage message : messages) {
      if (async) {
        client.sendAsync(message).thenAcceptAsync(reply -> {
          if (!reply.isSuccess()) {
            f.completeExceptionally(
                new AssertionError("Failed with reply " + reply));
          } else if (asyncReplyCount.incrementAndGet() == messages.length) {
            f.complete(null);
          }
        });
      } else {
        client.send(message);
      }
    }
    if (async) {
      f.join();
      Assert.assertEquals(messages.length, asyncReplyCount.get());
    }
  }

  Thread.sleep(cluster.getMaxTimeout() + 100);
  LOG.info(cluster.printAllLogs());

  cluster.getServerAliveStream().map(s -> s.getState().getLog())
      .forEach(log -> RaftTestUtil.assertLogEntries(log, async, term, messages));
}
 
Example 20
Project: myth   File: LogUtil.java   View Source Code Vote up 4 votes
public static void info(Logger logger, String format, Supplier<Object> supplier) {
    if (logger.isInfoEnabled()) {
        logger.info(format, supplier.get());
    }
}