Java logging framework --Log4j log

A, Log4j profile

Apache Log4J is an open source project (official website  http://jakarta.apache.org/log4j ), by using Log4J in the project, we can control the log information to the console, files, GUI components, or even database. We can control the output format of each log, the log is defined by the output level can be more flexible control log output process. Easy to debug the project.

1. Log4j components :

Log4j mainly consists of the following components:

Loggers is (Logger): controls the log output level and whether the output log;

Appenders (output): specify the output format of the log (to the console, files, etc.);

Layout (log format output device): controls the output format of the log information.

Log4j has a special logger called the "root", he is the root of all Logger, which means that all other logger will inherit directly or indirectly from root.

root logger can invoking the Logger.getRootLogger () method to get.

2.Appenders: to specify a log output to which place, you can specify the log output destination, Log4j commonly used output destination has about a few:

An output terminal type effect
ConsoleAppender The log output to the console
FileAppender The log output to a file
DailyRollingFileAppender The log output to a log file, and output to a new file every day
RollingFileAppender The output log information to a log file, and the size of the specified file, when the file size reaches a specified size, the document name automatically, while generating a new file
JDBCAppender Save the log information to the database

3.Layouts: placer Layouts format for log output control content, so that we can use the format of the output log needs, Log4j common Layouts:

Formatting type effect
HTMLLayout Log output formatted as an HTML table form
SimpleLayout Simple log output format for printing log format (info message)
PatternLayout The most powerful formatting period, according to a custom format output log, if you do not specify a format conversion, is to use the default format conversion
xml.XMLLayout XML export

4.Layout format: Log4j.properties in the configuration file, we define the log output level and the output terminal. Are arranged at the output of the output format of the log.

(1) Log4j using a C-like format layout log information printf function, specific placeholder and their meanings are:

Placeholder meaning
%m Output log information specified in the code
%p  Output priority, and DEBUG, INFO, etc.
%n Newline
%r Output to the output since the start of the log information on the number of milliseconds spent
%c Full name printed output statement belongs to the class
%t The log output produced thread full name
%d The server current time output, the default is in ISO8601, can also specify the format, such as:% d {yyyy, MM-dd day HH: mm: ss}
%l Time position of the output log, which includes the class name, threads, and the number of lines in the code
%F When the output file name where the log messages generated
%L The output of the code line number
%% Output a "%" character

(2)% can be added between the character modifier to control the minimum width, the maximum width of its embodiment and text

Placeholder meaning
%5c Output category name, the minimum width is 5, the right under 5, by default category <aligned
%-5c Output category name, the minimum width is 5, category <5, "_" is specified left-aligned, there will be spaces
%.5c Output category name, the maximum width is 5, category> 5. Will be left out of the multi-character truncated, <5 does not have spaces
% 20.30c Output category name <20 fill the spaces, and the right-aligned; output category name> characters 30 characters, it is outputted from the far left of the amputated

Second, Quick Start

首先在 maven 中引入 log4j 的依赖:

<!-- log日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

创建 Log4jTest 类,测试 Log4j 的使用:

  @Test
    public void testQuick() throws Exception{
//        开启log4j内置日志记录
        LogLog.setInternalDebugging(true);


//        初始化配置信息,在入门案例中暂不使用配置文件
        BasicConfigurator.configure();
//        获取日志记录器对象
        Logger logger = Logger.getLogger(Log4jDemo.class);
//        日志记录输出
        logger.info("hello log4j");

//        日志级别



        //设置日志输出级别为WARN,这将覆盖配置文件中设置的级别,只有日志级别高于WARN的日志才输出
            logger.setLevel(Level.WARN);
            logger.fatal("fatal");//严重错误,一般会造成系统崩溃并终止运行

            logger.error("error");//错误信息,不会影响系统运行
            logger.warn("warn");  //警告信息,可能会发生问题
            logger.info("info");  //运行信息,数据连接、网络连接、IO操作等等
            logger.debug("debug");//调试信息,一般在开发中使用,记录程序变量参数传递信息等等

            logger.trace("trace");//追踪信息,记录程序所有的流程信息



//        在获取一个日志记录器对象
        Logger logger1 = Logger.getLogger(Logger.class);

        logger1.fatal("fatal  logger1");//严重错误,一般会造成系统崩溃并终止运行

        logger1.error("error  logger1");//错误信息,不会影响系统运行
        logger1.warn("warn  logger1");  //警告信息,可能会发生问题
        logger1.info("info  logger1");  //运行信息,数据连接、网络连接、IO操作等等
        logger1.debug("debug  logger1");//调试信息,一般在开发中使用,记录程序变量参数传递信息等等

        logger1.trace("trace  logger1");//追踪信息,记录程序所有的流程信息

    }

这里首先通过 Logger.getLogger(Log4Test.class) 创建 Logger 实例,然后调用 BasicConfigurator.configure() 方法指定该 Logger 使用默认的配置信息,接着调用 looger.setLevel(Level.WARN) 设置 Logger 的日志输出级别为 WARN 。运行 main 函数,控制台将会输出 warn 以上的错误信息。控制台输出如下:

0 [main] INFO LoggerDemo.Log4jDemo  - hello log4j
5 [main] FATAL LoggerDemo.Log4jDemo  - fatal
5 [main] ERROR LoggerDemo.Log4jDemo  - error
5 [main] WARN LoggerDemo.Log4jDemo  - warn
6 [main] FATAL org.apache.log4j.Logger  - fatal  logger1
6 [main] ERROR org.apache.log4j.Logger  - error  logger1
6 [main] WARN org.apache.log4j.Logger  - warn  logger1
7 [main] INFO org.apache.log4j.Logger  - info  logger1
7 [main] DEBUG org.apache.log4j.Logger  - debug  logger1
7 [main] TRACE org.apache.log4j.Logger  - trace  logger1

注:如果没有调用 BasicConfigurator.configure() 方法,则运行 main 函数的时候则会报错,因为 Log4j 框架在运行的时候会加载项目路径下的 log4j.properties 配置文件(关于配置文件的使用,会在后面讲解)。而我们此时的项目中是没有该文件的。如果配置文件的名称不是 log4j.properties,则可以通过 PropertyConfigurator.configure(String configFilename) 指定配置文件的名称。

格式化器的使用

修改 Log4JTest 中的代码:

public class Log4JTest {
 
    public static void main(String[] args) {
        Logger logger = Logger.getLogger(Log4JTest.class);
        BasicConfigurator.configure();
        HTMLLayout layout = new HTMLLayout();
        // SimpleLayout layout = new SimpleLayout();
        try {
            FileAppender appender = new FileAppender(layout, "D:\\out.html", false);
            logger.addAppender(appender);
            //设置日志输出级别为info,这将覆盖配置文件中设置的级别,只有日志级别高于WARN的日志才输出
            logger.setLevel(Level.WARN);
            logger.debug("这是debug");
            logger.info("这是info");
            logger.warn("这是warn");
            logger.error("这是error");
            logger.fatal("这是fatal");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}

首先创建一个HTML格式的格式化器(HTMLLayout),然后创建文件输出端(FileAppender)指定输出端的格式为 HTML 格式,这里我指定输出路径为 D 盘下的 out.html 文件。然后通过 logger.addAppender(appender) 将文件输出端加载到 Logger 中。运行 main 函数,在 D 盘下会生成一个 out.html 文件,打开文件,里面的信息就是代码中输出的日志信息:

log4j.properties 配置文件的使用

上面使用代码的方式设置 Logger 的输出格式,这样在我们每个要输出日志的类上都得设置一遍配置未免也太麻烦了吧。有一种更加方便的方法,我们只需要在项目路径下新建 log4j.properties 配置文件,并配置日志的输出格式等信息,Log4J 框架会自动的加载配置文件,并将配置信息设置到 Logger 中。最简单的配置文件如下:

#配置根  Loggers控制日志的输出级别与日志是否输出
log4j.rootLogger=trace,console

#自定义logger对象设置
log4j.logger.LoggerDemo = info,file

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.console=org.apache.log4j.ConsoleAppender
#指定输出控制台
log4j.appender.console.Target = System.out
#指定布局,输出日志的格式
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.console.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n


#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.file=org.apache.log4j.FileAppender
#指定布局,输出日志的格式
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.file.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.file.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.file.encoding = UTF-8

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
#指定布局,输出日志的格式
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.rollingFile.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.rollingFile.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.rollingFile.encoding = UTF-8
#指定日志文件内容的大小
log4j.appender.rollingFile.maxFileSize = 1MB
#指定日志文件的数量
log4j.appender.rollingFile.maxBackupIndex = 10

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.dailyRollingFile=org.apache.log4j.DailyRollingFileAppender
#指定布局,输出日志的格式
log4j.appender.dailyRollingFile.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.dailyRollingFile.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.dailyRollingFile.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.dailyRollingFile.encoding = UTF-8
#指定日志输出规则
log4j.appender.dailyRollingFile.datePattern = '.'yyyy-MM-dd-HH-mm-ss


#mysql
log4j.appender.logDB=org.apache.log4j.jdbc.JDBCAppender
#指定布局,输出日志的格式
log4j.appender.logDB.layout=org.apache.log4j.PatternLayout

log4j.appender.logDB.Driver = com.mysql.jdbc.Driver
log4j.appender.logDB.URL = jdbc:mysql://localhost:3306/logs
log4j.appender.logDB.User = root
log4j.appender.logDB.Password = root
log4j.appender.logDB.Sql = INSERT INTO log(project_name,create_date,level,category,file_name,thread_name,line,all_category,message) values('itcast','%d{yyyy-MM-dd HH:mm:ss}','%p','%c','%F','%t','%L','%l','%m')

使用JDBCAppender导出日志格式时,数据库设计如下: 

DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `project_name` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '项目名',
  `create_date` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '创建时间',
  `level` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '优先级',
  `category` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '所在类的全名',
  `file_name` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '输出日志消息产生时所在的文件名称',
  `thread_name` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '日志事件的线程名',
  `line` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '行号',
  `all_category` varchar(255) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '日志事件的发生位置',
  `message` varchar(4000) COLLATE utf8_general_mysql500_ci DEFAULT NULL COMMENT '输出代码中指定的消息',
  PRIMARY KEY (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=30013 DEFAULT CHARSET=utf8 COLLATE=utf8_general_mysql500_ci;

 

发布了17 篇原创文章 · 获赞 11 · 访问量 7999

Guess you like

Origin blog.csdn.net/LOVE_Me__/article/details/104307802