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

The following examples show how to use org.slf4j.Logger#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: Bean.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
public static Class<?> getType(Object bean, String prop) {
	if (bean == null || prop == null)
		return null;
	try {
		Class<?> c = bean.getClass();
		String[] props = prop.split("\\.");
		Field field = null;
		for (String p : props) {
			field = c.getDeclaredField(p);
			if (field == null)
				return null;
			c = field.getType();
		}
		return c;
	} catch (Exception e) {
		Logger log = LoggerFactory.getLogger(Bean.class);
		log.error("Failed to get type of field "
				+ prop + " in " + bean, e);
		return null;
	}
}
 
Example 2
Source File: MdcActivationListenerIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testVerifyThatWithEnabledCorrelationAndLoggedErrorMdcErrorIdIsNotBlankWithSlf4j() {
    when(loggingConfiguration.isLogCorrelationEnabled()).thenReturn(true);
    Logger mockedLogger = mock(Logger.class);
    doAnswer(invocation -> assertMdcErrorIdIsNotEmpty()).when(mockedLogger).error(anyString(), any(Exception.class));

    assertMdcErrorIdIsEmpty();

    Transaction transaction = tracer.startRootTransaction(getClass().getClassLoader()).withType("request").withName("test");
    transaction.activate();
    mockedLogger.error("Some slf4j exception", new RuntimeException("Hello exception"));

    assertMdcErrorIdIsEmpty();

    transaction.deactivate().end();

    assertMdcErrorIdIsEmpty();
}
 
Example 3
Source File: ServletRegister.java    From vi with Apache License 2.0 6 votes vote down vote up
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 4
Source File: Configuration.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validates that the system is not using the horribly buggy Sun JAXP implementation.
 */
public static void validateNonSunJAXP() {
    Logger log = getLogger();
    String builderFactoryClass = DocumentBuilderFactory.newInstance().getClass().getName();
    log.debug("VM using JAXP parser {}", builderFactoryClass);

    if (builderFactoryClass.startsWith("com.sun")) {
        String errorMsg = "\n\n\nOpenSAML requires an xml parser that supports JAXP 1.3 and DOM3.\n"
                + "The JVM is currently configured to use the Sun XML parser, which is known\n"
                + "to be buggy and can not be used with OpenSAML.  Please endorse a functional\n"
                + "JAXP library(ies) such as Xerces and Xalan.  For instructions on how to endorse\n"
                + "a new parser see http://java.sun.com/j2se/1.5.0/docs/guide/standards/index.html\n\n\n";

        log.error(errorMsg);
        throw new Error(errorMsg);
    }
}
 
Example 5
Source File: WatchRequestTests.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
static void runTestWatchRequestClientTimeout(TestParameters p) throws Exception {
  final Logger LOG = p.log;

  CompletableFuture<RaftClientReply> watchReply;
  // watch 1000 which will never be committed
  // so client can not receive reply, and connection closed, throw TimeoutException.
  // We should not retry, because if retry, RaftClientImpl::handleIOException will random select a leader,
  // then sometimes throw NotLeaderException.
  watchReply = p.sendWatchRequest(1000, RetryPolicies.noRetry());

  try {
    watchReply.get();
    fail("runTestWatchRequestClientTimeout failed");
  } catch (Exception ex) {
    LOG.error("error occurred", ex);
    Assert.assertTrue(ex.getCause().getClass() == AlreadyClosedException.class ||
        ex.getCause().getClass() == RaftRetryFailureException.class);
    if (ex.getCause() != null) {
      if (ex.getCause().getCause() != null) {
        Assert.assertEquals(TimeoutIOException.class,
            ex.getCause().getCause().getClass());
      }
    }
  }
}
 
Example 6
Source File: JsonProvider.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
public List<FlowMap> getFlowMaps() {
	try (ZipStore store = ZipStore.open(file)) {
		List<String> files = store.getFiles("flow_mappings");
		List<FlowMap> maps = new ArrayList<>();
		for (String f : files) {
			byte[] data = store.get(f);
			String json = new String(data, "utf-8");
			JsonObject obj = new Gson().fromJson(json, JsonObject.class);
			FlowMap map = FlowMap.fromJson(obj);
			maps.add(map);
		}
		return maps;
	} catch (Exception e) {
		Logger log = LoggerFactory.getLogger(getClass());
		log.error("failed to read mapping files", e);
		return Collections.emptyList();
	}
}
 
Example 7
Source File: NettyTestUtility.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public static IMessage encodeDecode(IMessage msg, ChannelHandler[] encodeHandlers,
                                      ChannelHandler[] decodeHandlers, Logger logger)
        throws IOException {
    try {
        ByteBuf buf = encode(msg, logger, encodeHandlers);
        return decode(buf, logger, decodeHandlers);
    } catch (IOException e) {
        if (logger != null) {
            logger.error(e.getMessage(), e);
        }
        throw e;
    }
}
 
Example 8
Source File: Statistics.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
private void collectProviderInfos(ProductSystem system, IDatabase db) {

		TLongLongHashMap defaults = new TLongLongHashMap();
		String query = "select id, f_default_provider from tbl_exchanges";
		try {
			NativeSql.on(db).query(query, r -> {
				long defprov = r.getLong(2);
				if (defprov == 0L)
					return true;
				long eid = r.getLong(1);
				defaults.put(eid, defprov);
				return true;
			});
		} catch (Exception e) {
			Logger log = LoggerFactory.getLogger(getClass());
			log.error("Failed to collect default providers", e);
		}

		ProcessTable ptable = ProcessTable.create(db);
		for (ProcessLink link : system.processLinks) {
			long defaultP = defaults.get(link.exchangeId);
			if (defaultP == link.providerId) {
				defaultProviderLinkCount++;
			}
			List<ProcessProduct> products = ptable.getProviders(link.flowId);
			if (products == null || products.isEmpty())
				continue;
			if (products.size() == 1) {
				singleProviderLinkCount++;
			} else {
				multiProviderLinkCount++;
			}
		}
	}
 
Example 9
Source File: OpenTSDBReporterTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadFailedServerError(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse,
    @Mocked StatusLine statusLine,
    @Capturing Logger logger) throws IOException, InterruptedException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 500;
  }};

  MetricRegistry registry = new MetricRegistry();
  OpenTSDBReporter reporter = makeReporter();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    logger.error(anyString, withInstanceOf(IllegalStateException.class));
  }};
}
 
Example 10
Source File: PythonEditor.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
public String getScript() {
	try {
		var script = browser.evaluate("return getContent();");
		return script != null
				? script.toString()
				: "";
	} catch (Exception e) {
		Logger log = LoggerFactory.getLogger(getClass());
		log.error("failed to get script content", e);
		return "";
	}
}
 
Example 11
Source File: DefaultJavascriptLogger.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean error( JavascriptLog javascriptLog )
{
    Logger toUse =
        javascriptLog.getLoggerName() == null ? logger : LoggerFactory.getLogger( javascriptLog.getLoggerName() );

    if ( javascriptLog.getMessage() == null )
    {
        return Boolean.TRUE;
    }

    toUse.error( javascriptLog.getMessage() );
    return Boolean.TRUE;
}
 
Example 12
Source File: RxIris.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static <T> void dolog(final LogLevel level, final Logger log, final String format, Object... value) {
   switch (level) {
   case TRACE:
      if (log.isTraceEnabled())
         log.trace(format, value);
      break;

   case DEBUG:
      if (log.isDebugEnabled())
         log.debug(format, value);
      break;

   case INFO:
      if (log.isInfoEnabled())
         log.info(format, value);
      break;

   case WARN:
      if (log.isWarnEnabled())
         log.warn(format, value);
      break;

   case ERROR:
      if (log.isErrorEnabled())
         log.error(format, value);
      break;

   default:
      break;
   }
}
 
Example 13
Source File: Utils.java    From gate-core with GNU Lesser General Public License v3.0 5 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  - a Log4J severity level for the message
 * @param message - the message itself
 * @deprecated Log4J support will be removed in future, please use SLF4J
 */
@Deprecated
public static void logOnce (Logger logger, Object level, String message) {
  if(!alreadyLoggedMessages.contains(message)) { 
  	switch (level.toString()) {
  		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":
  		case "FATAL":
  			logger.error(message);
  			break;
  		default:
  			// unknown log level, should be impossible
 }
    alreadyLoggedMessages.add(message);
  }
}
 
Example 14
Source File: GFToSlf4jBridge.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void put(int level, String msg, Throwable exception) {
  Logger log = getLogger();
  MDC.put("tid", Long.toHexString(Thread.currentThread().getId()));
  switch (level) {
    case SEVERE_LEVEL:
    case ERROR_LEVEL:
      log.error(msg, exception);
      break;
    case WARNING_LEVEL:
      log.warn(msg, exception);
      break;
    case INFO_LEVEL:
    case CONFIG_LEVEL:
      log.info(msg, exception);
      break;
    case FINE_LEVEL:
      log.debug(msg, exception);
      break;
    case FINER_LEVEL:
    case FINEST_LEVEL:
      log.trace(msg, exception);
      break;
    default:
      log.debug(msg, exception);
      break;
  }
}
 
Example 15
Source File: LogUtil.java    From caravan with Apache License 2.0 4 votes vote down vote up
public static void error(Logger logger, String message, Throwable t, Map<String, String> tags) {
    logger.error(messageWithTag(message, tags), t);
}
 
Example 16
Source File: LoggerSpaceFactory4LogbackBuilderTest.java    From sofa-common-tools with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoggingLeveDynamicChange() throws Exception {
    String loggerName = "com.foo.Bar";
    AbstractLoggerSpaceFactory loggerSpaceFactory = loggerSpaceFactory4LogbackBuilder.build(
        LOG_SPACE_TEST, this.getClass().getClassLoader());
    Logger logger = loggerSpaceFactory.getLogger(loggerName);

    System.err.println("init level INFO ===");

    Assert.assertTrue(logger.isErrorEnabled());
    Assert.assertTrue(logger.isWarnEnabled());
    Assert.assertTrue(logger.isInfoEnabled());
    Assert.assertFalse(logger.isDebugEnabled());
    Assert.assertFalse(logger.isTraceEnabled());
    logger.error("error level===");
    logger.warn("warn level===");
    logger.info("info level===");
    logger.debug("debug level===");
    logger.trace("trace level===");

    System.err.println("Change level to Debug ===");
    Logger logger1 = loggerSpaceFactory.setLevel(loggerName, AdapterLevel.DEBUG);
    Assert.assertTrue(logger1 instanceof ch.qos.logback.classic.Logger && logger == logger1);
    Assert.assertTrue(logger.isErrorEnabled());
    Assert.assertTrue(logger.isWarnEnabled());
    Assert.assertTrue(logger.isInfoEnabled());
    Assert.assertTrue(logger.isDebugEnabled());
    Assert.assertFalse(logger.isTraceEnabled());
    logger.error("error level===");
    logger.warn("warn level===");
    logger.info("info level===");
    logger.debug("debug level===");
    logger.trace("trace level===");

    System.err.println("Change level to TRACE ===");
    Logger logger2 = loggerSpaceFactory.setLevel(loggerName, AdapterLevel.TRACE);
    Assert.assertTrue(logger2 instanceof ch.qos.logback.classic.Logger && logger == logger2);
    Assert.assertTrue(logger.isErrorEnabled());
    Assert.assertTrue(logger.isWarnEnabled());
    Assert.assertTrue(logger.isInfoEnabled());
    Assert.assertTrue(logger.isDebugEnabled());
    Assert.assertTrue(logger.isTraceEnabled());
    logger.error("error level===");
    logger.warn("warn level===");
    logger.info("info level===");
    logger.debug("debug level===");
    logger.trace("trace level===");
}
 
Example 17
Source File: ACSFactory.java    From freeacs with MIT License 4 votes vote down vote up
public static RemoteException error(Logger logger, Throwable t) throws RemoteException {
  String msg = "An exception occurred: " + t.getMessage();
  logger.error(msg, t);
  return new RemoteException(msg, t);
}
 
Example 18
Source File: AionBlockchainImpl.java    From aion with MIT License 3 votes vote down vote up
/**
 * Retrieves ranges of blocks from the pending block store for a specific blockchain height.
 *
 * @param level the blockchain height of interest
 * @param log the logger used for messages
 * @return a map containing all the block ranges that are stored in the pending block store at
 *     the given height. The map may be empty if there is no data stored for the given height.
 *     It may also contain several entries if there are multiple ranges starting at the given
 *     level due to the storage of different chains.
 */
public Map<ByteArrayWrapper, List<Block>> loadPendingBlocksAtLevel(long level, Logger log) {
    try {
        return repository.getPendingBlockStore().loadBlockRange(level, log);
    } catch (Exception e) {
        log.error("Unable to retrieve stored blocks from " + repository.toString() + " due to: ", e);
        return Collections.emptyMap();
    }
}
 
Example 19
Source File: LogUtil.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
/**
 * Write the appropriate error message to the log file
 *
 * @param log
 *            logger to write the message
 * @param message
 *            specific message to write to the log file
 * @param exception
 *            the exception which caused the log file entry
 */
public static void error(Logger log, String message, Throwable exception) {
    // Log the error with a message-safe exception.
    if (log.isErrorEnabled()) {
        Throwable loggingException = createLoggingException(exception);
        log.error(message, loggingException);
    }
}
 
Example 20
Source File: TinkerforgeErrorHandler.java    From openhab1-addons with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Logs errors using the given logger.
 * 
 * @param logger The logger to use as {@code Logger}.
 * @param message The message to log as {@code String}.
 * @param e The throwable to log as {@code Throwable}
 */
public static void handleError(Logger logger, String message, Throwable e) {
    logger.error("Tinkerforge Error: {} : {}", message, e.getMessage());
}