JAVA日志组件系列(一)logback1.0.3and sli4j1.6.4

    之前一直使用commons-logging和log4j的组合。今天有空之余,研究了一下logback与slf4j。
    LogBack将作为Log4j的替代,和slf4j组成新的日志系统的完整实现。LogBack分为三个模块:logback-core、logback-classic和logback-access。logback-core是其它两个模块的基础;logback-classic是log4j的一个改良版本; logback-access与Servlet容器集成提供通过Http来访问日志的功能。
    下面是最简单的logback的项目代码。

引用的包
logback-classic-1.0.3.jar
logback-core-1.0.3.jar
slf4j-api-1.6.4.jar


package com.panguso.phl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;

public class Test {
    private static Logger logger = LoggerFactory.getLogger(Test.class);

    public static void main(String[] args) throws Exception {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();

        String path = java.net.URLDecoder.decode(Test.class.getResource("/").getPath(), "utf8") + "logback.xml";
        configurator.doConfigure(path);

        logger.info("hello logback!");
        logger.info("classpath is {}" , path);
    }
}



logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
	<!-- appender -->
	<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n</pattern>
		</layout>
	</appender>
	<!-- log 通过 LoggerFactory.getLogger(name)取得 -->
	<logger name="myLog" additivity="true" level="info">
		<appender-ref ref="stdout" />
	</logger>
	<!-- root 默认日志配置 -->
	<root level="info">
		<appender-ref ref="stdout" />
	</root>
</configuration>

你可能感兴趣的:(logback)