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

The following are Jave code examples for showing how to use warn() 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: xitk   File: LogUtil.java   View Source Code Vote up 7 votes
public static void warn(Logger log, Throwable th, String msg) {
    if (!log.isWarnEnabled()) {
        return;
    }

    // this operation is expensive, hence don't abuse it.
    StackTraceElement[] traces = Thread.currentThread().getStackTrace();
    if (traces.length > 2) {
        StackTraceElement trace = traces[2];
        log.warn("({} {}) {}, {}: {}", trace.getMethodName(), trace.getLineNumber(), msg,
                th.getClass().getName(), getMessage(th));
    } else {
        log.warn("{}, {}: {}", msg, th.getClass().getName(), getMessage(th));
    }
    log.debug(msg, th);
}
 
Example 2
Project: incubator-ratis   File: LogUtils.java   View Source Code Vote up 6 votes
static <OUTPUT, THROWABLE extends Throwable> OUTPUT supplyAndLog(
    Logger log, CheckedSupplier<OUTPUT, THROWABLE> supplier, Supplier<String> name)
    throws THROWABLE {
  final OUTPUT output;
  try {
    output = supplier.get();
  } catch (Throwable t) {
    if (log.isTraceEnabled()) {
      log.trace("Failed to " + name.get(), t);
    } else if (log.isWarnEnabled()){
      log.warn("Failed to " + name.get() + ": " + t);
    }
    throw (THROWABLE)t;
  }

  if (log.isTraceEnabled()) {
    log.trace("Successfully supplied " + name.get());
  }
  return output;
}
 
Example 3
Project: incubator-ratis   File: JavaUtils.java   View Source Code Vote up 6 votes
/** Attempt to wait the given condition to return true multiple times. */
static void attempt(
    BooleanSupplier condition, int numAttempts, long sleepMs, String name, Logger log)
    throws InterruptedException {
  Objects.requireNonNull(condition, "condition == null");
  Preconditions.assertTrue(numAttempts > 0, () -> "numAttempts = " + numAttempts + " <= 0");
  Preconditions.assertTrue(sleepMs >= 0L, () -> "sleepMs = " + sleepMs + " < 0");

  for(int i = 1; i <= numAttempts; i++) {
    if (condition.getAsBoolean()) {
      return;
    }
    if (log != null && log.isWarnEnabled()) {
      log.warn("FAILED " + name + " attempt #" + i + "/" + numAttempts
          + ": sleep " + sleepMs + "ms and then retry.");
    }
    if (sleepMs > 0) {
      Thread.sleep(sleepMs);
    }
  }

  if (!condition.getAsBoolean()) {
    throw new IllegalStateException("Failed " + name + " for " + numAttempts + " attempts.");
  }
}
 
Example 4
Project: Vigilate   File: Metrics.java   View Source Code Vote up 6 votes
protected JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
    JsonObject chart = new JsonObject();
    chart.addProperty("chartId", chartId);
    try {
        JsonObject data = getChartData();
        if (data == null) {
            // If the data is null we don't send the chart.
            return null;
        }
        chart.add("data", data);
    } catch (Throwable t) {
        if (logFailedRequests) {
            logger.warn("Failed to get data for custom chart with id {}", chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example 5
Project: cornerstone   File: ServletRegister.java   View Source Code Vote up 6 votes
protected static final void regiesterVIServlet(ServletContext context,Logger logger){

        try {
            ServletRegistration.Dynamic asr = context.addServlet("VIApiServlet", VIApiServlet.class);

            if (asr != null) {
                asr.setLoadOnStartup(Integer.MAX_VALUE);
                asr.addMapping("/@in/api/*");
            } else {
                logger.warn("Servlet VIApiServlet already exists");
            }

            ServletRegistration ssr = context.addServlet("VIHttpServlet", StaticContentServlet.class);
            if (ssr != null) {
                ssr.addMapping("/@in/*");
            } else {
                logger.warn("Servlet VIHttpServlet already exists");
            }

        }catch (Throwable e){
            logger.error("VI register servlet failed",e);
        }
    }
 
Example 6
Project: OftenPorter   File: PortExecutor.java   View Source Code Vote up 6 votes
/**
 * 最后成功或异常的输出都调用这里。
 *
 * @param response
 * @param jResponse
 */
private final void doFinalWriteOf404(WRequest request, WResponse response, JResponse jResponse)
{
    try
    {
        Object rs = jResponse;
        if (responseHandle != null)
        {
            rs = responseHandle.toResponseOf404(request, response, jResponse);
        }
        response.write(rs);
    } catch (IOException e)
    {
        Throwable ex = getCause(e);
        Logger LOGGER = logger(null);
        LOGGER.warn(ex.getMessage(), ex);
    }
}
 
Example 7
Project: cornerstone   File: AppHandler.java   View Source Code Vote up 5 votes
@Override
public Object execute(String path, String user, int permission, Logger logger, Map<String, Object> params) throws Exception {
    Object rtn = "";
    AppInfo appInfo = ComponentManager.getStatus(AppInfo.class);

    String opPath = path.substring(startPath.length()).toLowerCase();
    if(!(user!=null && user.length()>2 && user.equals(appInfo.getAppOwner())) && !"uvtrace".equals(opPath)) {
        throw new NoPermissionException();
    }
    switch (opPath){
        case "markdown":
            if(!appInfo.isStatusSourceEnabled()){
                throw new Exception("can't markdwon. because statusSources be disabled!");
            }
            OwnerJudge.getInstance().toAbnormal();
            logger.warn(user + " markdown the app.");
            break;
        case "markup":
            if(!appInfo.isStatusSourceEnabled()){
                throw new Exception("can't markup. because statusSources be disabled!");
            }
            OwnerJudge.getInstance().toNormal();
            logger.warn(user + " markup the app.");
            break;
        case "enablestatussource":
            appInfo.enableStatusSource();
            logger.warn(user + " enable statusSources.");
            break;
        case "disablestatussource":
            appInfo.disableStatusSource();
            logger.warn(user + " disable statusSources.");
            break;
        case "uvtrace":
            eventLogger.fireEvent(HttpUtil.getJsonParamVal(params.get("name")));
            break;
    }
    return rtn;
}
 
Example 8
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 9
Project: openNaEF   File: DefaultNodeInfoFactory.java   View Source Code Vote up 5 votes
@Override
public NodeInfo createNodeInfo(NodeDto node) throws IOException {
    if (node == null) {
        throw new IllegalArgumentException();
    }
    Logger log = LoggerFactory.getLogger(getClass());
    try {
        String ipAddress = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.MANAGEMENT_IP);
        String snmpRO = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.SNMP_COMMUNITY);
        String userName = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.TELNET_ACCOUNT);
        String userPass = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.TELNET_PASSWORD);
        String adminName = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.ADMIN_ACCOUNT);
        String adminPass = DtoUtil.getStringOrNull(node, MPLSNMS_ATTR.ADMIN_PASSWORD);

        if (ipAddress == null) {
            throw new IllegalStateException("magament ip address is mandatory.");
        }
        if (snmpRO == null) {
            throw new IllegalStateException("SNMP community string (RO) is mandatory.");
        }

        NodeInfo nodeinfo = new NodeInfo(node.getName());
        InetAddress inetAddress = InetAddress.getByAddress(
                VossMiscUtility.getByteFormIpAddress(ipAddress));
        nodeinfo.addIpAddress(inetAddress);
        nodeinfo.setCommunityStringRO(snmpRO);
        nodeinfo.setUserAccount(userName);
        nodeinfo.setUserPassword(userPass);
        nodeinfo.setAdminAccount(adminName);
        nodeinfo.setAdminPassword(adminPass);
        nodeinfo.addSupportedProtocol(ProtocolPort.SNMP_V2C_GETBULK);
        nodeinfo.addSupportedProtocol(ProtocolPort.TELNET);
        return nodeinfo;
    } catch (UnknownHostException e) {
        log.warn("failed to create node-info: " + node.getName(), e);
        return null;
    }
}
 
Example 10
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 11
Project: incubator-ratis   File: JavaUtils.java   View Source Code Vote up 5 votes
/** Attempt to get a return value from the given supplier multiple times. */
static <RETURN, THROWABLE extends Throwable> RETURN attempt(
    CheckedSupplier<RETURN, THROWABLE> supplier,
    int numAttempts, long sleepMs, String name, Logger log)
    throws THROWABLE, InterruptedException {
  Objects.requireNonNull(supplier, "supplier == null");
  Preconditions.assertTrue(numAttempts > 0, () -> "numAttempts = " + numAttempts + " <= 0");
  Preconditions.assertTrue(sleepMs >= 0L, () -> "sleepMs = " + sleepMs + " < 0");

  for(int i = 1; i <= numAttempts; i++) {
    try {
      return supplier.get();
    } catch (Throwable t) {
      if (i == numAttempts) {
        throw t;
      }
      if (log != null && log.isWarnEnabled()) {
        log.warn("FAILED " + name + " attempt #" + i + "/" + numAttempts
            + ": " + t + ", sleep " + sleepMs + "ms and then retry.", t);
      }
    }

    if (sleepMs > 0) {
      Thread.sleep(sleepMs);
    }
  }
  throw new IllegalStateException("BUG: this line should be unreachable.");
}
 
Example 12
Project: Selenium-Foundation   File: ScreenshotUtils.java   View Source Code Vote up 5 votes
/**
 * Determine if the specified driver is capable of taking screenshots.
 * 
 * @param optDriver optional web driver object
 * @param logger SLF4J logger object
 * @return 'true' if driver can take screenshots; otherwise 'false
 */
public static boolean canGetArtifact(Optional<WebDriver> optDriver, Logger logger) {
    if (optDriver.isPresent()) {
        WebDriver driver = optDriver.get();
        if (driver instanceof TakesScreenshot) {
            return true;
        } else {
            String message = "This driver is not capable of taking a screenshot.  If a screenshot is desired, use"
                    + " a WebDriver implementation that supports screenshots. For more information, see https://"
                    + "seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/TakesScreenshot.html";
            logger.warn(message);
        }
    }
    return false;
}
 
Example 13
Project: rskj   File: AbstractValidationRule.java   View Source Code Vote up 5 votes
public void logErrors(Logger logger) {
    if (logger.isErrorEnabled()) {
        for (String msg : errors) {
            logger.warn("{} invalid: {}", getEntityClass().getSimpleName(), msg);
        }
    }
}
 
Example 14
Project: AppCoins-ethereumj   File: BlockHeaderRule.java   View Source Code Vote up 5 votes
public boolean validateAndLog(BlockHeader header, Logger logger) {
    ValidationResult result = validate(header);
    if (!result.success && logger.isErrorEnabled()) {
        logger.warn("{} invalid {}", getEntityClass(), result.error);
    }
    return result.success;
}
 
Example 15
Project: updatebot   File: Configuration.java   View Source Code Vote up 5 votes
public void warn(Logger log, String message, Throwable e) {
    if (printStream != null) {
        printStream.println(colored(COLOR_WARNING, "WARNING: " + message + " " + e));
        e.printStackTrace(printStream);
    } else {
        log.warn(message, e);
    }
}
 
Example 16
Project: servicebuilder   File: LogUtil.java   View Source Code Vote up 5 votes
public static void doLog(String s, LogLevel logLevel, Logger logger) {
    switch (logLevel) {
        case ERROR: {
            logger.error(s);
            break;
        }

        case WARN: {
            logger.warn(s);
            break;
        }

        case INFO: {
            logger.info(s);
            break;
        }

        case DEBUG: {
            logger.debug(s);
            break;
        }

        case TRACE: {
            logger.trace(s);
            break;
        }

        default: {
            logger.error(s);
            break;
        }
    }
}
 
Example 17
Project: nifi-registry   File: RunNiFiRegistry.java   View Source Code Vote up 5 votes
private synchronized void savePidProperties(final Properties pidProperties, final Logger logger) throws IOException {
    final String pid = pidProperties.getProperty(PID_KEY);
    if (!StringUtils.isBlank(pid)) {
        writePidFile(pid, logger);
    }

    final File statusFile = getStatusFile(logger);
    if (statusFile.exists() && !statusFile.delete()) {
        logger.warn("Failed to delete {}", statusFile);
    }

    if (!statusFile.createNewFile()) {
        throw new IOException("Failed to create file " + statusFile);
    }

    try {
        final Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(statusFile.toPath(), perms);
    } catch (final Exception e) {
        logger.warn("Failed to set permissions so that only the owner can read status file {}; "
                + "this may allows others to have access to the key needed to communicate with NiFi Registry. "
                + "Permissions should be changed so that only the owner can read this file", statusFile);
    }

    try (final FileOutputStream fos = new FileOutputStream(statusFile)) {
        pidProperties.store(fos, null);
        fos.getFD().sync();
    }

    logger.debug("Saved Properties {} to {}", new Object[]{pidProperties, statusFile});
}
 
Example 18
Project: happylifeplat-tcc   File: LogUtil.java   View Source Code Vote up 4 votes
public static void warn(Logger logger, Supplier<Object> supplier) {
    if (logger.isWarnEnabled()) {
        logger.warn(Objects.toString(supplier.get()));
    }
}
 
Example 19
Project: happylifeplat-tcc   File: LogUtil.java   View Source Code Vote up 4 votes
public static void warn(Logger logger, String format, Supplier<Object> supplier) {
    if (logger.isWarnEnabled()) {
        logger.warn(format, supplier.get());
    }
}
 
Example 20
Project: OftenPorter   File: PortExecutor.java   View Source Code Vote up 4 votes
public void doRequest(PreRequest req, WRequest request, WResponse response, boolean isInnerRequest)
{
    WObjectImpl wObject = null;
    try
    {

        PorterOfFun funPort = req.funPort;
        Porter classPort = req.classPort;

        Context context = req.context;
        InnerContextBridge innerContextBridge = context.innerContextBridge;
        UrlDecoder.Result result = req.result;


        if (!isInnerRequest && funPort.getMethodPortIn()
                .getPortFunType() == PortFunType.INNER)
        {
            exNotFoundClassPort(request, response, innerContextBridge.responseWhenException);
            return;
        }


        wObject = new WObjectImpl(pName, result, request, response, context, isInnerRequest);
        IAttributeFactory attributeFactory = iAttributeFactory;
        Object originRequest = request.getOriginalRequest();
        if (originRequest != null && originRequest instanceof IAttributeFactory)
        {
            attributeFactory = (IAttributeFactory) originRequest;
        }
        wObject.setIAttribute(attributeFactory);

        if (funPort.getMethodPortIn().getTiedType().isRest())
        {
            wObject.restValue = result.funTied();
        }

        ParamSource paramSource = getParamSource(wObject, classPort, funPort);
        wObject.setParamSource(paramSource);
        //全局通过检测
        dealtOfGlobalCheck(context, funPort, wObject, innerContextBridge, result);
    } catch (Exception e)
    {
        Throwable ex = getCause(e);
        response.toErr();
        Logger LOGGER = logger(null);
        if (LOGGER.isWarnEnabled())
        {
            LOGGER.warn(ex.getMessage(), ex);
        }
        if (responseWhenException)
        {
            JResponse jResponse = new JResponse(ResultCode.EXCEPTION);
            jResponse.setDescription(WPTool.getMessage(ex));
            try
            {
                response.write(jResponse);
            } catch (IOException e1)
            {
                LOGGER.warn(e1.getMessage(), e1);
            }
        }
        close(response);

    } finally
    {
        if (wObject != null)
        {
            wObject.invokeAfterInvokeListeners();
        }
    }
}