logback: 通用、可靠、快速靈活的日誌框架--配置樣例

1、簡介: html

      logback是一個可靠、通用、快速而又靈活的Java日誌框架。 聲稱要取代log4j.Logback is intended as a successor to the popular log4j projec java

      logback當前分紅三個模塊:logback-core,logback- classic和logback-access。 mysql

      logback-core是其它兩個模塊的基礎模塊。logback-classic是log4j的一個改良版本。 sql

      logback-classic完整實現SLF4J API使你能夠很方便地更換成其它日誌系統如log4j或JDK14 Logging。           logback-access訪問模塊與Servlet容器集成提供經過Http來訪問日誌的功能。 數據庫

      官網地址:http://logback.qos.ch/ apache

2、如何在項目中引入 app

     1.須要在maven項目的pom.xml中增長以下依賴,內容以下: 框架

<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!-- 若是須要將日誌輸出到數據庫,則須要引入以下兩個信賴 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.2.1</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>

2.若是須要將日誌輸出到數據庫如MYSQL數據庫,則須要在pom.xml中引入mysql-connector-java,c3p0(數據庫鏈接池),而且須要在數據庫中創建以下三張表,建表語句以下: 異步

能夠參考:http://logback.qos.ch/manual/appenders.html maven

# Logback: the reliable, generic, fast and flexible logging framework.
# Copyright (C) 1999-2010, QOS.ch. All rights reserved.
#
# See http://logback.qos.ch/license.html for the applicable licensing 
# conditions.
# This SQL script creates the required tables by ch.qos.logback.classic.db.DBAppender.
#
# It is intended for MySQL databases. It has been tested on MySQL 5.1.37 
# on Linux

BEGIN;
DROP TABLE IF EXISTS logging_event_property;
DROP TABLE IF EXISTS logging_event_exception;
DROP TABLE IF EXISTS logging_event;
COMMIT;

BEGIN;
CREATE TABLE logging_event 
  (
    timestmp         BIGINT NOT NULL,
    formatted_message  TEXT NOT NULL,
    logger_name       VARCHAR(254) NOT NULL,
    level_string      VARCHAR(254) NOT NULL,
    thread_name       VARCHAR(254),
    reference_flag    SMALLINT,
    arg0              VARCHAR(254),
    arg1              VARCHAR(254),
    arg2              VARCHAR(254),
    arg3              VARCHAR(254),
    caller_filename   VARCHAR(254) NOT NULL,
    caller_class      VARCHAR(254) NOT NULL,
    caller_method     VARCHAR(254) NOT NULL,
    caller_line       CHAR(4) NOT NULL,
    event_id          BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY
  );
COMMIT;
BEGIN;
CREATE TABLE logging_event_property
  (
    event_id	      BIGINT NOT NULL,
    mapped_key        VARCHAR(254) NOT NULL,
    mapped_value      TEXT,
    PRIMARY KEY(event_id, mapped_key),
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
  );
COMMIT;
BEGIN;
CREATE TABLE logging_event_exception
  (
    event_id         BIGINT NOT NULL,
    i                SMALLINT NOT NULL,
    trace_line       VARCHAR(254) NOT NULL,
    PRIMARY KEY(event_id, i),
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
  );
COMMIT;

3.在classpath目錄下建立logback.xml,內容以下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
	<!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑 -->
	<property name="LOG_HOME" value="/home/data/javawork/RocketMQTest/log" />

	<!-- 控制檯輸出 -->
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
				%msg%n</pattern>
		</encoder>
	</appender>

	<!-- 按照天天生成日誌文件 -->
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日誌文件輸出的文件名 -->
			<FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log
			</FileNamePattern>
			<!--日誌文件保留天數 -->
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
				%msg%n</pattern>
		</encoder>
		<!--日誌文件最大的大小 -->
		<triggeringPolicy
			class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<MaxFileSize>10MB</MaxFileSize>
		</triggeringPolicy>
	</appender>

	<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
		<!--日誌異步到數據庫 -->
		<connectionSource
			class="ch.qos.logback.core.db.DriverManagerConnectionSource">
			<!--鏈接池 -->
			<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">
				<driverClass>com.mysql.jdbc.Driver</driverClass>
				<url>jdbc:mysql://172.168.29.250:3306/test</url>
				<user>root</user>
				<password>root</password>
			</dataSource>
		</connectionSource>
	</appender>

	<!-- show parameters for hibernate sql 專爲 Hibernate 定製 -->
	<logger name="org.hibernate.type.descriptor.sql.BasicBinder"
		level="TRACE" />
	<logger name="org.hibernate.type.descriptor.sql.BasicExtractor"
		level="DEBUG" />
	<logger name="org.hibernate.SQL" level="DEBUG" />
	<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
	<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />

	<!--myibatis log configure -->
	<logger name="com.apache.ibatis" level="TRACE" />
	<logger name="java.sql.Connection" level="DEBUG" />
	<logger name="java.sql.Statement" level="DEBUG" />
	<logger name="java.sql.PreparedStatement" level="DEBUG" />

	<!-- 日誌輸出級別 -->
	<root level="INFO">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
		<appender-ref ref="DB" />
	</root>
</configuration>

4.在具體的JAVA類中,使用logback

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


// 定義一個全局的記錄器,經過LoggerFactory獲取
private final static Logger log = LoggerFactory.getLogger(Producer.class);
log.info("日誌內容");
相關文章
相關標籤/搜索