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

The following examples show how to use org.slf4j.Logger#warn() . 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: DynoJedisPipeline.java    From dyno with Apache License 2.0 6 votes vote down vote up
private void releaseConnection() {
    if (connection != null) {
        try {
            connection.getContext().reset();
            connection.getParentConnectionPool().returnConnection(connection);
            if (pipelineEx.get() != null) {
                connPool.getHealthTracker().trackConnectionError(connection.getParentConnectionPool(),
                        pipelineEx.get());
                pipelineEx.set(null);
            }
            connection = null;
        } catch (Exception e) {
            Logger.warn(String.format("Failed to return connection in Dyno Jedis Pipeline, %s", getHostInfo()), e);
        }
    }
}
 
Example 2
Source File: LogAspect.java    From WeBASE-Sign with Apache License 2.0 6 votes vote down vote up
@Around("logPointCut()")
public Object methodAround(ProceedingJoinPoint point) throws Throwable {
    Instant startTime = Instant.now();
    Class targetClass = point.getTarget().getClass();
    MethodSignature methodSignature = (MethodSignature) point.getSignature();
    String methodName = methodSignature.getName();
    Object[] args = point.getArgs();
    Logger logger = LoggerManager.getLogger(targetClass);
    // log args of param in controller
    // if args contains BindingResult(recursive of request entity and itself), stack over flow
    logger.debug("startTime:{} methodName:{} args:{}", startTime, methodName,
        JsonUtils.toJSONString(this.excludeBindingResult(args)));
    Object result = null;
    try {
        result = point.proceed();
    } catch (Throwable throwable) {
        logger.warn("fail request. methodName:{} ", methodName, throwable);
        throw throwable;
    }

    String resultStr = Optional.ofNullable(result).map(JsonUtils::toJSONString).orElse(null);
    logger.debug("methodName:{} usedTime:{} result:{}", methodName,
        Duration.between(startTime, Instant.now()), resultStr);
    return result;
}
 
Example 3
Source File: Slf4jEventSender.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Override this to easily change the logging level etc.
 */
protected void performLogging(Logger log, Marker marker, String logMessage) {
    if (loggingLevel == Level.INFO) {
        log.info(marker, logMessage);
    } else if (loggingLevel == Level.DEBUG) {
        log.debug(marker, logMessage);
    } else if (loggingLevel == Level.ERROR) {
        log.error(marker, logMessage);
    } else if (loggingLevel == Level.TRACE) {
        log.trace(marker, logMessage);
    } else if (loggingLevel == Level.WARN) {
        log.warn(marker, logMessage);
    } else {
        log.info(marker, logMessage);
    }
}
 
Example 4
Source File: AlbianLoggerService.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public <T extends Exception> void warnAndThrow(String loggerName,
                                               Class<T> cls, Exception e, String eInfo, String format,
                                               Object... values) throws RuntimeException {
    Logger logger = getLogger(loggerName);
    if (null == logger)
        return;
    if (logger.isWarnEnabled()) {
        String id = AlbianServiceRouter.getLogIdService().makeLoggerId();
        String msg = getWarnMsg(e, format, values);
        String tMsg = String.format("%s | %s.", id, msg);
        logger.warn(tMsg);
        Class[] clss = new Class[]{String.class};
        Object[] vars = new Object[]{"Warn:" + id + "," + eInfo};
        T throwObject = null;
        try {
            throwObject = (T) AlbianReflect.newInstance(cls, clss, vars);
        } catch (Exception e1) {
            throw new RuntimeException(e);
        }
        if (null != throwObject)
            throw new RuntimeException(throwObject);
    }
}
 
Example 5
Source File: ImportWizardUtil.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
static void handleException(
    Exception e,
    ImportWizard importWizard,
    BindingResult result,
    Logger logger,
    String dataImportOption) {
  File file = importWizard.getFile();

  if (logger.isWarnEnabled()) {
    logger.warn(
        format(
            "Import of file [%s] failed for action [%s]",
            Optional.ofNullable(file).map(File::getName).orElse("UNKNOWN"), dataImportOption),
        e);
  }

  result.addError(
      new ObjectError("wizard", "<b>Your import failed:</b><br />" + e.getLocalizedMessage()));
}
 
Example 6
Source File: LogbackListAppenderTest.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Test
public void addAndRemoveAppender() {
	String testString = "Hello";
	Logger logger = LoggerFactory.getLogger(LogbackListAppenderTest.class);
	LogbackListAppender appender = new LogbackListAppender();
	// class
	appender.addToLogger(LogbackListAppenderTest.class);
	logger.warn(testString);
	assertThat(appender.getFirstLog()).isNotNull();

	appender.clearLogs();
	appender.removeFromLogger(LogbackListAppenderTest.class);
	logger.warn(testString);
	assertThat(appender.getFirstLog()).isNull();

	// name
	appender.clearLogs();
	appender.addToLogger("com.vip.vjtools.test.log");
	logger.warn(testString);
	assertThat(appender.getFirstLog()).isNotNull();

	appender.clearLogs();
	appender.removeFromLogger("com.vip.vjtools.test.log");
	logger.warn(testString);
	assertThat(appender.getFirstLog()).isNull();
}
 
Example 7
Source File: WindowLayout.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
static void initialize() {
	Logger log = LoggerFactory.getLogger(WindowLayout.class);
	try {
		File dir = getDir();
		File xmi = new File(dir, "workbench.xmi");
		if (!xmi.exists()) {
			copyXmi();
			return;
		}
		File resetFlag = new File(dir, "_reset_layout");
		if (!resetFlag.exists()) {
			log.trace("window layout file exists {}", xmi);
			return;
		}

		log.info("reset window layout");
		copyXmi();
		if (!resetFlag.delete()) {
			log.warn("failed to delete reset flag; "
					+ "adding shutdown hook: " + resetFlag);
			resetFlag.deleteOnExit();
		}
	} catch (Exception e) {
		log.error("failed to initialize workbench layout", e);
	}
}
 
Example 8
Source File: CallerInformationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodLogger() throws Exception {
    final ListAppender app = ctx.getListAppender("Method").clear();
    final Logger logger = LoggerFactory.getLogger("MethodLogger");
    logger.info("More messages.");
    logger.warn("CATASTROPHE INCOMING!");
    logger.error("ZOMBIES!!!");
    logger.warn("brains~~~");
    logger.info("Itchy. Tasty.");
    final List<String> messages = app.getMessages();
    assertEquals("Incorrect number of messages.", 5, messages.size());
    for (final String message : messages) {
        assertEquals("Incorrect caller method name.", "testMethodLogger", message);
    }
}
 
Example 9
Source File: RefResolverUtils.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Convenience method to encode the given string to UTF-8 compliant URL string.
 * @param toEncode the string to encode
 * @param log the logger to log exceptions to
 * @return the encoded string
 */
public static String urlEncode( String toEncode, Logger log )
{
    try
    {
        return URLEncoder.encode( toEncode, "UTF-8" );
    }
    catch( UnsupportedEncodingException ex )
    {
        log.warn( "Unable to encode string to UTF-8 URL: " + toEncode, ex );
        return null;
    }
}
 
Example 10
Source File: RequestReaderDelegator.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public void init( @Service Iterable<ServiceReference<RequestReader>> requestReaderReferences )
{
    Logger logger = LoggerFactory.getLogger( getClass() );
    Identity requestreaderdelegator = StringIdentity.identityOf( "requestreaderdelegator" );

    // Add custom readers first
    for( ServiceReference<RequestReader> requestReader : requestReaderReferences )
    {
        if( !requestReader.identity().equals(requestreaderdelegator) )
        {
            logger.info( "Registered request reader:" + requestReader.identity() );
            registerRequestReader( requestReader.get() );
        }
    }

    // Add defaults
    ResourceBundle defaultRequestReaders = ResourceBundle.getBundle( "org.apache.polygene.library.rest.server.rest-server" );

    String requestReaderClasses = defaultRequestReaders.getString( "requestreaders" );
    logger.info( "Using request readers:" + requestReaderClasses );
    for( String className : requestReaderClasses.split( "," ) )
    {
        try
        {
            Class readerClass = module.descriptor().classLoader().loadClass( className.trim() );
            RequestReader writer = (RequestReader) module.newObject( readerClass );
            registerRequestReader( writer );
        }
        catch( ClassNotFoundException e )
        {
            logger.warn( "Could not register request reader " + className, e );
        }
    }
}
 
Example 11
Source File: SynchronizationUtils.java    From PeerWasp with MIT License 5 votes vote down vote up
/**
 * Loads the given resource and returns a new ImageView instance.
 * @param resourceName specifying image
 * @return image view with associated resource.
 */
private static ImageView getImageByName(String resourceName) {
	try (InputStream in = SynchronizationUtils.class.getResourceAsStream(resourceName)) {
		if (in != null) {
			return new ImageView(new Image(in));
		}
	} catch (IOException e) {
		Logger logger = LoggerFactory.getLogger(SynchronizationUtils.class);
		logger.warn("Could not load icon '{}'.", resourceName, e);
	}
	return new ImageView();
}
 
Example 12
Source File: DockerClientBuilder.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public DockerClient build() {
    if (dockerHttpClient != null) {
        return DockerClientImpl.getInstance(
            dockerClientConfig,
            dockerHttpClient
        );
    } else if (dockerCmdExecFactory != null) {
        return DockerClientImpl.getInstance(dockerClientConfig)
            .withDockerCmdExecFactory(dockerCmdExecFactory);
    } else {
        Logger log = LoggerFactory.getLogger(DockerClientBuilder.class);
        log.warn(
            "'dockerHttpClient' should be set." +
                "Falling back to Jersey, will be an error in future releases."
        );

        return DockerClientImpl.getInstance(
            dockerClientConfig,
            new JerseyDockerHttpClient.Builder()
                .dockerHost(dockerClientConfig.getDockerHost())
                .sslConfig(dockerClientConfig.getSSLConfig())
                .build()
        );
    }
}
 
Example 13
Source File: JdbcUtils.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public static ConnectionProvider createConnectionProvider(final ConfiguredObject<?> parent,
                                                          final JDBCSettings settings,
                                                          final Logger logger)
        throws SQLException
{
    String connectionPoolType = settings.getConnectionPoolType() == null
            ? DefaultConnectionProviderFactory.TYPE
            : settings.getConnectionPoolType();

    JDBCConnectionProviderFactory connectionProviderFactory =
            JDBCConnectionProviderFactory.FACTORIES.get(connectionPoolType);
    if (connectionProviderFactory == null)
    {
        logger.warn("Unknown connection pool type: {}.  No connection pooling will be used", connectionPoolType);
        connectionProviderFactory = new DefaultConnectionProviderFactory();
    }

    Map<String, String> providerAttributes = new HashMap<>();
    Set<String> providerAttributeNames = new HashSet<>(connectionProviderFactory.getProviderAttributeNames());
    providerAttributeNames.retainAll(parent.getContextKeys(false));
    for (String attr : providerAttributeNames)
    {
        providerAttributes.put(attr, parent.getContextValue(String.class, attr));
    }

    return connectionProviderFactory.getConnectionProvider(settings.getConnectionUrl(),
                                                           settings.getUsername(),
                                                           settings.getPassword(),
                                                           providerAttributes);
}
 
Example 14
Source File: WriterUtil.java    From kieker with Apache License 2.0 5 votes vote down vote up
public static void close(final Closeable closeable, final Logger logger) {
	try {
		closeable.close();
	} catch (final IOException e) {
		logger.warn("Caught exception while closing '{}'.", closeable.getClass(), e);
	}
}
 
Example 15
Source File: DebugSql.java    From database with Apache License 2.0 5 votes vote down vote up
public static void logWarning(String sqlType, Logger log, Metric metric, String errorCode, String sql, Object[] args,
                        Options options, Throwable t) {
  if (log.isWarnEnabled()) {
    String msg = logMiddle(' ', sqlType, metric, errorCode, sql, args, options);
    log.warn(msg, t);
  }
}
 
Example 16
Source File: LogUtils.java    From tankbattle with MIT License 4 votes vote down vote up
public static void warn(String message, Object... params) {
    Logger log = getLogger(getClassName());
    log.warn(message, params);
}
 
Example 17
Source File: LogUtil.java    From caravan with Apache License 2.0 4 votes vote down vote up
public static void warn(Logger logger, String message, Map<String, String> tags) {
    logger.warn(messageWithTag(message, tags));
}
 
Example 18
Source File: BlobUtils.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Moves the temporary <tt>incomingFile</tt> to its permanent location where it is available for
 * use (not thread-safe!).
 *
 * @param incomingFile
 * 		temporary file created during transfer
 * @param jobId
 * 		ID of the job this blob belongs to or <tt>null</tt> if job-unrelated
 * @param blobKey
 * 		BLOB key identifying the file
 * @param storageFile
 *      (local) file where the blob is/should be stored
 * @param log
 *      logger for debug information
 * @param blobStore
 *      HA store (or <tt>null</tt> if unavailable)
 *
 * @throws IOException
 * 		thrown if an I/O error occurs while moving the file or uploading it to the HA store
 */
static void moveTempFileToStore(
		File incomingFile, @Nullable JobID jobId, BlobKey blobKey, File storageFile,
		Logger log, @Nullable BlobStore blobStore) throws IOException {

	try {
		// first check whether the file already exists
		if (!storageFile.exists()) {
			try {
				// only move the file if it does not yet exist
				Files.move(incomingFile.toPath(), storageFile.toPath());

				incomingFile = null;

			} catch (FileAlreadyExistsException ignored) {
				log.warn("Detected concurrent file modifications. This should only happen if multiple" +
					"BlobServer use the same storage directory.");
				// we cannot be sure at this point whether the file has already been uploaded to the blob
				// store or not. Even if the blobStore might shortly be in an inconsistent state, we have
				// to persist the blob. Otherwise we might not be able to recover the job.
			}

			if (blobStore != null) {
				// only the one moving the incoming file to its final destination is allowed to upload the
				// file to the blob store
				blobStore.put(storageFile, jobId, blobKey);
			}
		} else {
			log.warn("File upload for an existing file with key {} for job {}. This may indicate a duplicate upload or a hash collision. Ignoring newest upload.", blobKey, jobId);
		}
		storageFile = null;
	} finally {
		// we failed to either create the local storage file or to upload it --> try to delete the local file
		// while still having the write lock
		if (storageFile != null && !storageFile.delete() && storageFile.exists()) {
			log.warn("Could not delete the storage file {}.", storageFile);
		}
		if (incomingFile != null && !incomingFile.delete() && incomingFile.exists()) {
			log.warn("Could not delete the staging file {} for blob key {} and job {}.", incomingFile, blobKey, jobId);
		}
	}
}
 
Example 19
Source File: LogUtil.java    From hmily with Apache License 2.0 2 votes vote down vote up
/**
 * Warn.
 *
 * @param logger   the logger
 * @param supplier the supplier
 */
public static void warn(Logger logger, Supplier<Object> supplier) {
    if (logger.isWarnEnabled()) {
        logger.warn(Objects.toString(supplier.get()));
    }
}
 
Example 20
Source File: LogUtil.java    From myth with Apache License 2.0 2 votes vote down vote up
/**
 * Warn.
 *
 * @param logger   the logger
 * @param format   the format
 * @param supplier the supplier
 */
public static void warn(Logger logger, String format, Supplier<Object> supplier) {
    if (logger.isWarnEnabled()) {
        logger.warn(format, supplier.get());
    }
}