下面列出了org.slf4j.Logger#isTraceEnabled ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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());
}
}
public static boolean isEnabledFor(Logger logger, LogLevel level) {
switch (level) {
case TRACE:
return logger.isTraceEnabled();
case DEBUG:
return logger.isDebugEnabled();
case INFO:
return logger.isInfoEnabled();
case WARN:
return logger.isWarnEnabled();
case ERROR:
return logger.isErrorEnabled();
}
return false;
}
@Around("(execution (public * org.jasig.cas..*.*(..))) && !(execution( * org.jasig.cas..*.set*(..)))")
public Object traceMethod(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object returnVal = null;
final Logger logger = this.getLog(proceedingJoinPoint);
final String methodName = proceedingJoinPoint.getSignature().getName();
try {
if (logger.isTraceEnabled()) {
final Object[] args = proceedingJoinPoint.getArgs();
final String arguments;
if (args == null || args.length == 0) {
arguments = "";
} else {
arguments = Arrays.deepToString(args);
}
logger.trace("Entering method [{}] with arguments [{}]", methodName, arguments);
}
returnVal = proceedingJoinPoint.proceed();
return returnVal;
} finally {
logger.trace("Leaving method [{}] with return value [{}].", methodName,
(returnVal != null ? returnVal.toString() : "null"));
}
}
@Override
public boolean shouldLog(int level, String category) {
Logger logger = getLogger(category);
LogLevel logLevel = getLogLevel(level);
switch (logLevel) {
case TRACE:
return logger.isTraceEnabled();
case DEBUG:
return logger.isDebugEnabled();
case INFO:
return logger.isInfoEnabled();
case WARN:
return logger.isWarnEnabled();
case ERROR:
return logger.isErrorEnabled();
default:
return true;
}
}
@Override
public boolean shouldLog(int level, String category){
Logger logger = getLogger(category);
LogLevel logLevel = getLogLevel(level);
switch (logLevel) {
case TRACE:
return logger.isTraceEnabled();
case DEBUG:
return logger.isDebugEnabled();
case INFO:
return logger.isInfoEnabled();
case WARN:
return logger.isWarnEnabled();
case ERROR:
return logger.isErrorEnabled();
default:
return true;
}
}
protected int subNumber(String name) {
if (counter != null) {
try {
return counter.incr(name);
} catch (Exception e) {
Logger log = Log.get("sumk.seq");
if (log.isTraceEnabled()) {
log.trace(e.getLocalizedMessage(), e);
} else {
log.debug(e.toString());
}
}
}
int sub = (ThreadLocalRandom.current().nextInt(0x100) << 16);
sub |= ((int) System.nanoTime()) & 0xFF00;
return sub | (localSeq(name) & 0xFF);
}
/**
* Deserialize the given byte string to an object using the given reader, employing the given codec algorithm.
*
* @param reader object reader
* @param byteString byte string to deserialize
* @param codec codec
* @param logger logger
* @param <T> object type of the deserialized object
* @return deserialized object
* @throws IOException in case of deserialization errors
*/
public static <T> T readValue(ObjectReader reader, ByteString byteString, Codec codec, Logger logger)
throws IOException {
if (logger.isTraceEnabled()) {
// Costly conversion to UTF-8. Avoid if possible
ByteSource bs = new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return codec.decompress(byteString.newInput());
}};
final String value = bs.asCharSource(StandardCharsets.UTF_8).read();
logger.trace("Attempting to read {}", value);
// Could reuse the value but to avoid so that logger level doesn't impact the program flow
// Since level is trace, user probably doesn't care for performance right now
// return reader.readValue(value);
}
try (InputStream is = codec.decompress(byteString.newInput())) {
return reader.readValue(is);
}
}
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;
}
protected void validate(Validatable validatable, ValidationErrors errors) {
try {
validatable.validate();
} catch (ValidationException e) {
Logger log = LoggerFactory.getLogger(Screen.class);
if (log.isTraceEnabled()) {
log.trace("Validation failed", e);
} else if (log.isDebugEnabled()) {
log.debug("Validation failed: " + e);
}
ComponentsHelper.fillErrorMessages(validatable, e, errors);
}
}
public void read(String path, boolean required, Logger log)
{
if (path == null)
{
throw new NullPointerException("Path value cannot be null");
}
if (log != null && log.isTraceEnabled())
{
log.trace("Attempting to read configuration file at: {}", path);
}
URL url = findURL(path);
if (url != null)
{
read(url, required, log);
}
else
{
String msg = "Could not find configuration file at: "+path;
if (log != null)
{
log.debug(msg);
}
if (required)
{
throw new ResourceNotFoundException(msg);
}
}
}
/**
* Unmarshall a Document from an InputSteam.
*
* @param parserPool the ParserPool instance to use
* @param inputStream the InputStream to unmarshall
* @return the unmarshalled XMLObject
* @throws XMLParserException if there is a problem parsing the input data
* @throws UnmarshallingException if there is a problem unmarshalling the parsed DOM
*/
public static XMLObject unmarshallFromInputStream(ParserPool parserPool, InputStream inputStream)
throws XMLParserException, UnmarshallingException {
Logger log = getLogger();
log.debug("Parsing InputStream into DOM document");
Document messageDoc = parserPool.parse(inputStream);
Element messageElem = messageDoc.getDocumentElement();
if (log.isTraceEnabled()) {
log.trace("Resultant DOM message was:");
log.trace(XMLHelper.nodeToString(messageElem));
}
log.debug("Unmarshalling DOM parsed from InputStream");
Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem);
if (unmarshaller == null) {
log.error("Unable to unmarshall InputStream, no unmarshaller registered for element "
+ XMLHelper.getNodeQName(messageElem));
throw new UnmarshallingException(
"Unable to unmarshall InputStream, no unmarshaller registered for element "
+ XMLHelper.getNodeQName(messageElem));
}
XMLObject message = unmarshaller.unmarshall(messageElem);
log.debug("InputStream succesfully unmarshalled");
return message;
}
@Override
public void visitEnd() {
Logger log = Log.get("sumk.asm");
String methodName = info.getMethod().getName();
Type[] args = info.getArgumentTypes();
Collections.sort(argPojos);
if (log.isTraceEnabled()) {
log.trace("{}.{}():{}", info.getMethod().getDeclaringClass().getName(), methodName, argPojos);
}
String[] argNames = info.getArgNames();
String[] signatures = info.getSignatures();
int size = argNames.length;
if (argPojos.size() < size) {
log.error("{}.{},real param size:{},but is {}", info.getMethod().getDeclaringClass().getName(), methodName,
size, argPojos.size());
SumkException.throwException(123253, "failed to parse parameter because parameter size not satisfied");
}
for (int i = 0; i < size; i++) {
LocalArg pojo = argPojos.get(i);
if (!args[i].getDescriptor().equals(pojo.desc)) {
log.error("{}.{},i:{},index:{},except:{},indeed:{}", info.getMethod().getDeclaringClass().getName(),
methodName, i, pojo.index, args[i].getDescriptor(), pojo.desc);
SumkException.throwException(123253, "failed to parse parameter");
}
argNames[i] = pojo.name;
signatures[i] = pojo.signature;
}
}
/**
* Traces the fact that a method has exited normally.
*
* @param log The Logger to log to.
* @param method The name of the method.
* @param traceEnterId The correlation Id obtained from a traceEnter call.
* @param args Additional arguments to log.
*/
public static void traceLeave(Logger log, String method, long traceEnterId, Object... args) {
if (!log.isTraceEnabled()) {
return;
}
if (args.length == 0) {
log.trace("LEAVE {}@{} (elapsed={}us).", method, traceEnterId, ELAPSED_MICRO.apply(traceEnterId));
} else {
log.trace("LEAVE {}@{} {} (elapsed={}us).", method, traceEnterId, args, ELAPSED_MICRO.apply(traceEnterId));
}
}
private static void logDeclaredData ()
{
// Note: Logger initialization has been differed until now
final Logger logger = LoggerFactory.getLogger(WellKnowns.class);
if (logger.isTraceEnabled()) {
for (Field field : WellKnowns.class.getDeclaredFields()) {
try {
logger.trace("{}= {}", field.getName(), field.get(null));
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
}
@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;
}
}
/**
* Uses the {@link ServiceLoader} to load all SPI implementations of the
* passed class
*
* @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>.
*/
@Nonnull
@ReturnsMutableCopy
public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass,
@Nonnull final ClassLoader aClassLoader,
@Nullable final Logger aLogger)
{
ValueEnforcer.notNull (aSPIClass, "SPIClass");
ValueEnforcer.notNull (aClassLoader, "ClassLoader");
final Logger aRealLogger = aLogger != null ? aLogger : LOGGER;
if (aRealLogger.isTraceEnabled ())
aRealLogger.trace ("Trying to retrieve all SPI implementations of " + aSPIClass);
if (!s_aCacheInterface.hasAnnotation (aSPIClass))
if (LOGGER.isWarnEnabled ())
LOGGER.warn (aSPIClass + " should have the @IsSPIInterface annotation");
final ServiceLoader <T> aServiceLoader = ServiceLoader.<T> load (aSPIClass, aClassLoader);
final ICommonsList <T> ret = new CommonsArrayList <> ();
// We use the iterator to be able to catch exceptions thrown
// when loading SPI implementations (e.g. the SPI implementation class does
// not exist)
final Iterator <T> aIterator = aServiceLoader.iterator ();
while (aIterator.hasNext ())
{
try
{
final T aInstance = aIterator.next ();
if (!s_aCacheImplementation.hasAnnotation (aInstance))
if (LOGGER.isWarnEnabled ())
LOGGER.warn (aInstance + " should have the @IsSPIImplementation annotation");
ret.add (aInstance);
}
catch (final Exception ex)
{
aRealLogger.error ("Unable to load an SPI implementation of " + aSPIClass, ex);
}
}
if (aRealLogger.isDebugEnabled ())
aRealLogger.debug ("Finished retrieving all " + ret.size () + " SPI implementations of " + aSPIClass);
return ret;
}
private void logOperation(final String operation, final Auditable entity, final String user,
final Serializable id, final Object[] state, final String[] propertyNames, final Type[] types) {
final Logger log = LOGS.computeIfAbsent(entity.getClass().getSimpleName(), k -> LoggerFactory.getLogger("AUDIT." + k));
if (log.isTraceEnabled()) {
final String className = entity.getClass().getSimpleName();
final Set<String> prohibited = prohibitedFields.get(className);
final StringBuilder line = new StringBuilder();
line.append(operation);
line.append(",\"");
line.append(className);
line.append("\",\"");
if (id == null || (id instanceof Number && ((Number) id).longValue() <= 0L)) {
line.append("N/A");
} else {
line.append(id);
}
line.append("\",\"");
line.append(user);
line.append("\",\"");
line.append(entity.getGuid());
line.append('"');
if (state != null) {
for (int i = 0; i < propertyNames.length; i++) {
final Type type = types[i];
if (type.isCollectionType()) {
continue; // skip collections
}
final String prop = propertyNames[i];
final Object value = state[i];
line.append(",\"");
line.append(prop);
line.append(":");
if (prohibited == null || !prohibited.contains(prop)) {
if (type.isEntityType()) {
if (Hibernate.isInitialized(value)) {
line.append(value);
} else {
line.append("lazy");
}
} else {
if (value instanceof String) {
line.append(((String) value).replace('"','\''));
} else {
line.append(value);
}
}
} else {
line.append("[prohibited]");
}
line.append("\"");
}
}
log.trace(line.toString());
}
}
/**
* Traces the fact that a method entry has occurred.
*
* @param log The Logger to log to.
* @param context Identifying context for the operation. For example, this can be used to differentiate between
* different instances of the same object.
* @param method The name of the method.
* @param args The arguments to the method.
* @return A generated identifier that can be used to correlate this traceEnter with its corresponding traceLeave.
* This is usually generated from the current System time, and when used with traceLeave it can be used to log
* elapsed call times.
*/
public static long traceEnterWithContext(Logger log, String context, String method, Object... args) {
if (!log.isTraceEnabled()) {
return 0;
}
long time = CURRENT_TIME.get();
log.trace("ENTER {}::{}@{} {}.", context, method, time, args);
return time;
}
/**
* trace level
* @param logger
* @param s
* @param objs
*/
public static void trace(Logger logger,String s,Object... objs){
if(logger.isTraceEnabled()){
logger.trace(s, objs);
}
}