Untitled

 avatar
unknown
plain_text
4 days ago
2.5 kB
5
Indexable
package eu.unicreditgroup.eu.gemo.application.services;

import org.apache.log4j.Logger;

/**
 * A global logger utility class that wraps log4j functionality.
 */
public class Logger {

    // Private constructor to prevent instantiation
    private Logger() {}

    // Method to get the logger for the calling class
    private static Logger getLogger() {
        return Logger.getLogger(Thread.currentThread().getStackTrace()[2].getClassName());
    }

    // Method for info level logging
    public static void info(String message) {
        getLogger().info(getFullClassName() + " " + message);
    }

    // Method for debug level logging
    public static void debug(String message) {
        getLogger().debug(getFullClassName() + " " + message);
    }

    // Method for error level logging
    public static void error(String message) {
        getLogger().error(getFullClassName() + " " + message);
    }

    // Method for warn level logging
    public static void warn(String message) {
        getLogger().warn(getFullClassName() + " " + message);
    }

    // Method for fatal level logging
    public static void fatal(String message) {
        getLogger().fatal(getFullClassName() + " " + message);
    }

    // Method for logging exceptions
    public static void error(String message, Throwable throwable) {
        getLogger().error(getFullClassName() + " " + message, throwable);
    }

    // Helper method to get the full class name including the entire class hierarchy (including parent classes)
    private static String getFullClassName() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        String callerClass = stackTrace[2].getClassName();
        
        // Load the Class object for the caller class
        try {
            Class<?> clazz = Class.forName(callerClass);
            StringBuilder classNameChain = new StringBuilder();

            // Traverse the parent classes and build the full class name chain
            while (clazz != null) {
                classNameChain.insert(0, clazz.getSimpleName());
                clazz = clazz.getSuperclass(); // Move to the parent class
                if (clazz != null) {
                    classNameChain.insert(0, " -> "); // Add separator between classes
                }
            }

            return classNameChain.toString();
        } catch (ClassNotFoundException e) {
            return callerClass; // In case ClassNotFoundException occurs, fallback to the simple class name
        }
    }
}
Leave a Comment