当前位置: 首页 > 工具软件 > Simple-Log > 使用案例 >

commons-logging 分析之: org.apache.commons.logging.impl.SimpleLog

弓玉书
2023-12-01

分析info 日志

public class Main {
    public static void main(String[] args) {
        Log logger = LogFactory.getLog(Main.class);
        //**重点**
        logger.info("message");
    }
}

SimpleLog初始化

SimpleLog静态初始化

触发初始化的地方:
//org.apache.commons.logging.impl.LogFactoryImpl::createLogFromClass
c = Class.forName(logAdapterClassName, true, currentCL);

 // Initialize class attributes.
    // Load properties file, if found.
    // Override with system properties.
    static {
        // Add props from the resource simplelog.properties
        // 从simplelog.properties 载入属性到 simpleLogProps 中
        InputStream in = getResourceAsStream("simplelog.properties");
        if(null != in) {
            try {
                simpleLogProps.load(in);
                in.close();
            } catch(java.io.IOException e) {
                // ignored
            }
        }
        // static protected final String systemPrefix = "org.apache.commons.logging.simplelog.";
        // 是否显示日志:org.apache.commons.logging.simplelog.showlogname,  默认值:false
        showLogName = getBooleanProperty( systemPrefix + "showlogname", showLogName);
        // org.apache.commons.logging.simplelog.showShortLogname 是否显示短日志名称  默认值:true
        showShortName = getBooleanProperty( systemPrefix + "showShortLogname", showShortName);
        // org.apache.commons.logging.simplelog.showdatetime 是否显示时间 默认值:false 
        showDateTime = getBooleanProperty( systemPrefix + "showdatetime", showDateTime);

        if(showDateTime) {
        //static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz";
        //static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
            //org.apache.commons.logging.simplelog.dateTimeFormat 时间格式化, 默认值: yyyy/MM/dd HH:mm:ss:SSS zzz
            dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat",
                                               dateTimeFormat);
            try {
                dateFormatter = new SimpleDateFormat(dateTimeFormat);
            } catch(IllegalArgumentException e) {
                // If the format pattern is invalid - use the default format
                dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
                dateFormatter = new SimpleDateFormat(dateTimeFormat);
            }
        }
    }

SimpleLog 构造初始化

  public SimpleLog(String name) {

        logName = name;

        // Set initial log level
        // Used to be: set default log level to ERROR
        // IMHO it should be lower, but at least info ( costin ).
        //设置默认级别为 info 
        setLevel(SimpleLog.LOG_LEVEL_INFO);
// static protected final String systemPrefix = "org.apache.commons.logging.simplelog.";
        // Set log level from properties
        //org.apache.commons.logging.simplelog.log.com.aya.Main
        String lvl = getStringProperty(systemPrefix + "log." + logName);
        int i = String.valueOf(name).lastIndexOf(".");
        // 遍历用户包:找到对应的日志级别
        //org.apache.commons.logging.simplelog.log.com.aya
        //org.apache.commons.logging.simplelog.log.com
        while(null == lvl && i > -1) {
            name = name.substring(0,i);
            lvl = getStringProperty(systemPrefix + "log." + name);
            i = String.valueOf(name).lastIndexOf(".");
        }
        // org.apache.commons.logging.simplelog.defaultlog 用户配置的默认级别
        if(null == lvl) {
            lvl =  getStringProperty(systemPrefix + "defaultlog");
        }

        if("all".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_ALL);
        } else if("trace".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_TRACE);
        } else if("debug".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_DEBUG);
        } else if("info".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_INFO);
        } else if("warn".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_WARN);
        } else if("error".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_ERROR);
        } else if("fatal".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_FATAL);
        } else if("off".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_OFF);
        }

    }

获取属性

  1. 从系统环境变量中获取,不为null就返回
  2. 从simpleLogProps 中获取(从simplelog.properties 载入的)
   private static String getStringProperty(String name) {
        String prop = null;
        try {

            prop = System.getProperty(name);
        } catch (SecurityException e) {
            ; // Ignore
        }
        return (prop == null) ? simpleLogProps.getProperty(name) : prop;
    }

SimpleLog 属性总结

复制配置: https://blog.csdn.net/gxmark/article/details/7338253
新建配置文件:simplelog.properties

org.apache.commons.logging.simplelog.defaultlog=trace
org.apache.commons.logging.simplelog.log.XXXXXX=debug
org.apache.commons.logging.simplelog.showlogname=true
org.apache.commons.logging.simplelog.showShortLogname=true
org.apache.commons.logging.simplelog.showdatetime=true
org.apache.commons.logging.simplelog.dateTimeFormat=yyyy-MM-dd hh:mm:ss

日志打印分析

    public final void info(Object message) {

        if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
            log(SimpleLog.LOG_LEVEL_INFO,message,null);
        }
    }

是否启用日志级别 isLevelEnabled

    /**
     * Is the given log level currently enabled?
     *
     * @param logLevel is this level enabled?
     */
    protected boolean isLevelEnabled(int logLevel) {
        // log level are numerically ordered so can use simple numeric
        // comparison
        // 日志级别是否大于等于当前日志级别
        return (logLevel >= currentLogLevel);
    }

打印日志

  • 拼接日志内容
    • showDateTime(时间)
    • type(日志级别)
    • showShortName(用户类的简单名称)
    • t (异常信息)
  • 打印
 protected void log(int type, Object message, Throwable t) {
        // Use a string buffer for better performance
        StringBuffer buf = new StringBuffer();

        // Append date-time if so configured
        if(showDateTime) {
            Date now = new Date();
            String dateText;
            synchronized(dateFormatter) {
                dateText = dateFormatter.format(now);
            }
            buf.append(dateText);
            buf.append(" ");
        }

        // Append a readable representation of the log level
        switch(type) {
            case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
            case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
            case SimpleLog.LOG_LEVEL_INFO:  buf.append("[INFO] ");  break;
            case SimpleLog.LOG_LEVEL_WARN:  buf.append("[WARN] ");  break;
            case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
            case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
        }

        // Append the name of the log instance if so configured
        if( showShortName) {
            if( shortLogName==null ) {
                // Cut all but the last component of the name for both styles
                shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
                shortLogName =
                    shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
            }
            buf.append(String.valueOf(shortLogName)).append(" - ");
        } else if(showLogName) {
            buf.append(String.valueOf(logName)).append(" - ");
        }

        // Append the message
        buf.append(String.valueOf(message));

        // Append stack trace if not null
        if(t != null) {
            buf.append(" <");
            buf.append(t.toString());
            buf.append(">");

            java.io.StringWriter sw= new java.io.StringWriter(1024);
            java.io.PrintWriter pw= new java.io.PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            buf.append(sw.toString());
        }

        // Print to the appropriate destination
        write(buf);

    }

打印

    protected void write(StringBuffer buffer) {
    // 系统错误输出
        System.err.println(buffer.toString());

    }

控制台输出

2018-06-19 04:37:01 [INFO] Main - message
 类似资料: