下面列出了org.slf4j.Logger#isWarnEnabled ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public <T extends Exception> void warnAndThrow(String loggerName,
Class<T> cls, 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(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(e1);
}
if (null != throwObject)
throw new RuntimeException(throwObject);
}
}
/** Attempt to wait the given condition to return true multiple times. */
static void attempt(
BooleanSupplier condition, int numAttempts, TimeDuration sleepTime, String name, Logger log)
throws InterruptedException {
Objects.requireNonNull(condition, "condition == null");
Preconditions.assertTrue(numAttempts > 0, () -> "numAttempts = " + numAttempts + " <= 0");
Preconditions.assertTrue(!sleepTime.isNegative(), () -> "sleepTime = " + sleepTime + " < 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 " + sleepTime + " and then retry.");
}
sleepTime.sleep();
}
if (!condition.getAsBoolean()) {
throw new IllegalStateException("Failed " + name + " for " + numAttempts + " attempts.");
}
}
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);
}
final THROWABLE throwable = JavaUtils.cast(t);
throw throwable;
}
if (log.isTraceEnabled()) {
log.trace("Successfully supplied " + name.get() + ": " + output);
}
return output;
}
/**
* If there is an existing file with given path, then try to roll it over with
* a suffix like -01-01 in the name. If rolling fails for some reason then log
* a warning and try to use rolled over file name.
*/
public String rollFileIfRequired(String logfile, Logger logger) {
final File logFile = new File(logfile);
if (logFile.exists()) {
final File oldMain = ManagerLogWriter.getLogNameForOldMainLog(logFile,
false);
if (!logFile.renameTo(oldMain)) {
logfile = oldMain.getPath();
if (logger.isWarnEnabled()) {
logger.info(Gfxd_EVENT_ERROR_LOGGER, logFile, oldMain);
}
}
else {
logfile = logFile.getPath();
}
}
return logfile;
}
/**
* If there is an existing file with given path, then try to roll it over with
* a suffix like -01-01 in the name. If rolling fails for some reason then log
* a warning and try to use rolled over file name.
*/
public String rollFileIfRequired(String logfile, Logger logger) {
final File logFile = new File(logfile);
if (logFile.exists()) {
final File oldMain = ManagerLogWriter.getLogNameForOldMainLog(logFile,
false);
if (!logFile.renameTo(oldMain)) {
logfile = oldMain.getPath();
if (logger.isWarnEnabled()) {
logger.info(Gfxd_DB_SYNCHRONIZER_16, logFile, oldMain);
}
}
else {
logfile = logFile.getPath();
}
}
return logfile;
}
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(), th.getMessage());
} else {
log.warn("{}, {}: {}", msg, th.getClass().getName(), th.getMessage());
}
if (th instanceof RuntimeException) {
log.warn(msg, th);
} else {
log.debug(msg, th);
}
}
static <THROWABLE extends Throwable> void runAndLog(
Logger log, CheckedRunnable<THROWABLE> op, Supplier<String> opName)
throws THROWABLE {
try {
op.run();
} catch (Throwable t) {
if (log.isTraceEnabled()) {
log.trace("Failed to " + opName.get(), t);
} else if (log.isWarnEnabled()){
log.warn("Failed to " + opName.get() + ": " + t);
}
throw t;
}
if (log.isTraceEnabled()) {
log.trace("Successfully ran " + opName.get());
}
}
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);
}
final THROWABLE throwable = JavaUtils.cast(t);
throw throwable;
}
if (log.isTraceEnabled()) {
log.trace("Successfully supplied " + name.get() + ": " + output);
}
return output;
}
public static int getLoggerLevel(Logger logger) {
if (logger == null) {
throw new NullPointerException("logger");
}
if (logger.isTraceEnabled()) {
return TRACE_LEVEL;
}
if (logger.isDebugEnabled()) {
return DEBUG_LEVEL;
}
if (logger.isInfoEnabled()) {
return INFO_LEVEL;
}
if (logger.isWarnEnabled()) {
return WARN_LEVEL;
}
if (logger.isErrorEnabled()) {
return ERROR_LEVEL;
}
return DISABLE_LEVEL;
}
private static boolean matches(Logger logger, LogLevel logLevel, String log)
{
boolean isEnabled = true;
switch (logLevel)
{
case DEBUG:
isEnabled = logger.isDebugEnabled();
break;
case INFO:
isEnabled = logger.isInfoEnabled();
break;
case WARNING:
isEnabled = logger.isWarnEnabled();
break;
case ERROR:
isEnabled = logger.isErrorEnabled();
break;
default:
}
return isEnabled && pattern.matcher(log).matches();
}
/**
* If there is an existing file with given path, then try to roll it over with
* a suffix like -01-01 in the name. If rolling fails for some reason then log
* a warning and try to use rolled over file name.
*/
public String rollFileIfRequired(String logfile, Logger logger) {
final File logFile = new File(logfile);
if (logFile.exists()) {
final File oldMain = ManagerLogWriter.getLogNameForOldMainLog(logFile,
false);
if (!logFile.renameTo(oldMain)) {
logfile = oldMain.getPath();
if (logger.isWarnEnabled()) {
logger.info(Gfxd_DB_SYNCHRONIZER_16, logFile, oldMain);
}
}
else {
logfile = logFile.getPath();
}
}
return logfile;
}
/**
* Logs the specified exception if it is {@linkplain #isExpected(Throwable) unexpected}.
*/
public static void logIfUnexpected(Logger logger, Channel ch, String debugData, Throwable cause) {
if (!logger.isWarnEnabled() || isExpected(cause)) {
return;
}
logger.warn("{} Unexpected exception: {}", ch, debugData, cause);
}
/**
* Logs a warning message about an invalid record.
*/
public static void warnInvalidRecord(Logger logger, String logPrefix, DnsRecordType type, ByteBuf content) {
if (logger.isWarnEnabled()) {
final String dump = ByteBufUtil.hexDump(content);
logger.warn("{} Skipping invalid {} record: {}",
logPrefix, type.name(), dump.isEmpty() ? "<empty>" : dump);
}
}
private void flush() {
Logger logWriter = config.getLog();
if (logWriter == null)
logWriter = LOGGER;
for (T r : records) {
if (logWriter.isWarnEnabled()) {
logWriter.info(String.valueOf(r));
}
}
records.clear();
timestamp = System.currentTimeMillis();
}
/**
* Uses the {@link ServiceLoader} to load all SPI implementations of the
* passed class and return only the first instance.
*
* @param <T>
* The implementation type to be loaded
* @param aSPIClass
* The SPI interface class. May not be <code>null</code>.
* @param aClassLoader
* The class loader to use for the SPI loader. May not be
* <code>null</code>.
* @param aLogger
* An optional logger to use. May be <code>null</code>.
* @return A collection of all currently available plugins. Never
* <code>null</code>.
*/
@Nullable
public static <T> T getFirstSPIImplementation (@Nonnull final Class <T> aSPIClass,
@Nonnull final ClassLoader aClassLoader,
@Nullable final Logger aLogger)
{
final Logger aRealLogger = aLogger != null ? aLogger : LOGGER;
final ICommonsList <T> aAll = getAllSPIImplementations (aSPIClass, aClassLoader, aRealLogger);
if (aAll.isEmpty ())
{
// No SPI implementation found
return null;
}
if (aAll.size () > 1)
{
// More than one implementation found
if (aRealLogger.isWarnEnabled ())
aRealLogger.warn ("Requested only one SPI implementation of " +
aSPIClass +
" but found " +
aAll.size () +
" - using the first one. Details: " +
aAll);
}
return aAll.getFirst ();
}
@Override
public void run(DeviceDriverContext context, Object value) {
Logger log = context.getLogger();
switch (lg.getLevel()) {
case TRACE:
if (log.isTraceEnabled()) {
log.trace(message());
}
break;
case DEBUG:
if (log.isDebugEnabled()) {
log.debug(message());
}
break;
case INFO:
if (log.isInfoEnabled()) {
log.info(message());
}
break;
case WARN:
if (log.isWarnEnabled()) {
log.warn(message());
}
break;
case ERROR:
if (log.isErrorEnabled()) {
log.error(message());
}
break;
default:
if (log.isDebugEnabled()) {
log.debug(message());
}
break;
}
}
public static void warn(Logger logger, String format, Supplier<Object> supplier) {
if (logger.isWarnEnabled()) {
logger.warn(format, supplier.get());
}
}
@Override
public boolean isEnabled(final Logger logger)
{
return logger.isWarnEnabled();
}
/**
* Write the appropriate warning 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 warn(Logger log, String message, Throwable exception) {
// Log the error with a message-safe exception.
if (log.isWarnEnabled()) {
Throwable loggingException = createLoggingException(exception);
log.warn(message, loggingException);
}
}
/**
* 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());
}
}