【Log】Log4j以及commons-logging使用

来源:互联网 发布:北京青少年行知园地图 编辑:程序博客网 时间:2024/06/06 06:57

1、单独使用log4j

1)、项目结构:

             

2)、OnlyLog4jTest内容

package com.log4j.wzq;import org.apache.log4j.Logger;/** * @Author:wangzhenqing * @Date:2015年03月16日15:32:18 * @Description:只有log4j,测试类 */public class OnlyLog4jTest {    private Logger logger = Logger.getLogger(OnlyLog4jTest.class);    public static void main(String[] args) {        OnlyLog4jTest onlyLog4jTest = new OnlyLog4jTest();        onlyLog4jTest.printInfo();    }    public void printInfo(){        logger.debug("debugInfo");        logger.info("info");        logger.error("errorInfo");        logger.fatal("fatalInfo");        logger.warn("warnInfo");    }}
3)、直接运行出错。

4)、修改,增加log4j.properties

  log4j.properties增加地址为:src/main/resources,需要修改代码,在文件中加载log4j.properties      

PropertyConfigurator.configure(PropertyConfigurator.class.getResourceAsStream("/log4j.properties"));
      log4j.properties内容,输出到控制台和文件      
log4j.rootLogger = Debug, stdout, file# 定义stdout的输出类型log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%p] %m%n# 定义file输出类型log4j.appender.file = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.file = log.txtlog4j.appender.file.layout = org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%p] %m%n
5)、至此,成功输出内容到控制台
2015-03-17 15:39:57 [DEBUG] debugInfo2015-03-17 15:39:57 [INFO] info2015-03-17 15:39:57 [ERROR] errorInfo2015-03-17 15:39:57 [FATAL] fatalInfo2015-03-17 15:39:57 [WARN] warnInfo

2、单独使用commons-logging

1)、OnlyCommonsLogTest内容

package com.log4j.wzq;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * @Author:wangzhenqing * @Date:2015年03月17日16:48:06 * @Description:单独使用commons-logging */public class OnlyCommonsLogTest {    public static void main(String[] args) {        OnlyCommonsLogTest onlyCommonsLogTest = new OnlyCommonsLogTest();        onlyCommonsLogTest.printInfo();    }    public void printInfo() {        Log log = LogFactory.getLog(OnlyCommonsLogTest.class);        log.debug("debugInfo");        log.info("info");        log.error("errorInfo");        log.fatal("fatalInfo");        log.warn("warnInfo");        System.out.println(log.getClass());    }}

2)、不加载任何配置文件,输出


3)、在src/main/resources增加commons-logging.properties,指定Log实现,文件内容为:

org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
输出使用的日志即为:class org.apache.commons.logging.impl.SimpleLog

3、结合使用log4j以及commons-logging

1)、在路径下加载commons-logging以及log4j包。

2)、直接运行class,结果





0 0
原创粉丝点击