zoukankan      html  css  js  c++  java
  • log4j2 工具类

    public class LoggerUtil {
        /**
         * 获取最原始被调用的堆栈信息
         *
         * @return
         */
        public static StackTraceElement findCaller() {
            // 获取堆栈信息
            StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
            if (null == callStack) return null;
    
            // 最原始被调用的堆栈信息
            StackTraceElement caller = null;
            // 日志类名称
            String logClassName = LoggerUtil.class.getName();
            // 循环遍历到日志类标识
            boolean isEachLogClass = false;
            // 遍历堆栈信息,获取出最原始被调用的方法信息
            for (StackTraceElement s : callStack) {
                // 遍历到日志类
                if (logClassName.equals(s.getClassName())) {
                    isEachLogClass = true;
                }
                // 下一个非日志类的堆栈,就是最原始被调用的方法
                if (isEachLogClass) {
                    if (!logClassName.equals(s.getClassName())) {
                        isEachLogClass = false;
                        caller = s;
                        break;
                    }
                }
            }
            return caller;
        }
    
        /**
         * 自动匹配请求类名,生成logger对象,此处 logger name 值为 [className].[methodName]()
         *
         * @return
         */
        private static Logger logger() {
            // 最原始被调用的堆栈对象
            StackTraceElement caller = findCaller();
            if (null == caller) return LoggerFactory.getLogger(LoggerUtil.class);
            Logger log = LoggerFactory.getLogger(caller.getClassName() + "." + caller.getMethodName());
            return log;
        }
    
    
        public static void trace(String msg) {
            trace(msg, null);
        }
    
        public static void trace(String msg, Throwable e) {
            logger().trace(msg, e);
        }
    
        public static void debug(String msg) {
            debug(msg, null);
        }
    
        public static void debug(String msg, Throwable e) {
            logger().debug(msg, e);
        }
    
        public static void info(String msg) {
            info(msg, null);
        }
    
        public static void info(String msg, Throwable e) {
            logger().info(msg, e);
        }
    
        public static void warn(String msg) {
            warn(msg, null);
        }
    
        public static void warn(String msg, Throwable e) {
            logger().warn(msg, e);
        }
    
        public static void error(String msg) {
            error(msg, null);
        }
    
        public static void error(String msg, Throwable e) {
            logger().error(msg, e);
        }
    }
  • 相关阅读:
    正则表达式
    HDU 2066 多源最短路
    UVA 11039 模拟
    Concrete Mathematics Chapter 1 Warmups
    List differences between JAVA and C++
    uva 11107Life Forms
    poj 1509 Glass Beads
    poj 3581
    网络流建图
    图论算法----网络流
  • 原文地址:https://www.cnblogs.com/zuge/p/7661662.html
Copyright © 2011-2022 走看看