
org.slf4j.plus.ExceptionLoggerFactory Maven / Gradle / Ivy
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slf4j.plus;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.slf4j.Logger;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
/**
* {@link LoggerFactory} for {@link ExceptionLogger}
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE) // @checkstyle:ok
public class ExceptionLoggerFactory {
/**
* The {@link ExceptionLogger} class
*/
@Setter
@NonNull
private static Class extends ExceptionLogger> loggerClass = ExceptionLogger.class;
/**
* Get a new {@link ExceptionLogger} instance.
*
* @param clazz the log class
* @return {@link ExceptionLogger}
*/
public static ExceptionLogger getLogger(@NonNull Class> clazz) {
return getLogger(LoggerFactory.getLogger(clazz));
}
/**
* Get a new {@link ExceptionLogger} instance.
*
* @param name the log name
* @return {@link ExceptionLogger}
*/
public static ExceptionLogger getLogger(@NonNull String name) {
return getLogger(LoggerFactory.getLogger(name));
}
/**
* Get a new {@link ExceptionLogger} instance.
*
* @param delegate {@link Logger}
* @return {@link ExceptionLogger}
*/
public static ExceptionLogger getLogger(@NonNull Logger delegate) {
try {
Constructor extends ExceptionLogger> constructor = loggerClass.getDeclaredConstructor(Logger.class);
constructor.setAccessible(true);
return constructor.newInstance(delegate);
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException("Failed to create logger instance", e);
}
}
/**
* Get a new {@link ExceptionLogger} instance. Note: This method uses {@link Throwable#getStackTrace()} to get the
* class name.
*
* @return {@link ExceptionLogger}
*/
public static ExceptionLogger currentClass() {
return getLogger(new Throwable().getStackTrace()[1].getClassName());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy