All Downloads are FREE. Search and download functionalities are using the official Maven repository.

delombok.io.github.qsy7.logging.util.ExceptionUtil Maven / Gradle / Ivy

The newest version!
// Generated by delombok at Fri Apr 08 14:43:06 EDT 2022
package io.github.qsy7.logging.util;

import io.github.qsy7.logging.ContextualLoggable;
import io.github.qsy7.logging.enumeration.LogLevel;
import java.security.SecureRandom;
import java.util.Base64;
import org.slf4j.LoggerFactory;

public class ExceptionUtil {
  public static final SecureRandom random = new SecureRandom();
  public static final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
  public static int idLength = 8;

  public static void onException(final ContextualLoggable contextualLoggable, final String typeName, final String methodName, final Object[] arguments, final Throwable throwable) {
    onException(typeName, methodName, arguments, throwable);
    // print contextual information
    LogLevel.ERROR.log(LoggerFactory.getLogger(typeName), "Contextual Details:\n{}", contextualLoggable.printContextualInformation());
  }

  public static void onException(final String typeName, final String methodName, final Object[] arguments, final Throwable throwable) {
    LogLevel.ERROR.log(LoggerFactory.getLogger(typeName), "{}({})\n{}", methodName, arguments, getStackTrace(throwable, getExceptionId()));
  }

  public static String getExceptionId() {
    byte[] buffer = new byte[idLength];
    random.nextBytes(buffer);
    return encoder.encodeToString(buffer);
  }

  public static String getStackTrace(final Throwable throwable, final String exceptionId) {
    final StringBuilder buffer = new StringBuilder();
    buffer.append("Exception ID: " + exceptionId + "\n");
    buffer.append(throwable.getClass() + "\n");
    if (throwable.getMessage() != null) {
      buffer.append(throwable.getMessage());
      buffer.append("\n");
    }
    if (throwable.getCause() != null) {
      buffer.append(throwable.getCause().getMessage());
      buffer.append("\n");
    }
    for (final StackTraceElement stackTraceElement : throwable.getStackTrace()) {
      buffer.append("\t" + stackTraceElement.toString() + "\n");
    }
    return buffer.toString();
  }

  @java.lang.SuppressWarnings("all")
  private ExceptionUtil() {
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy