java服务端Log4j日志记录(文件和数据库方式)

要在自己的程序中使用Log4j,首先需要将commons-logging.jar和logging-log4j-1.2.9.jar导入到构建路径中。

然后再将log4j.properties放到src根目录下。

1、不使用配置,单纯用程序记录日志的方式

package test;

import org.apache.log4j.*;

public class Log4jLayout2 {
    public static void main(String[] args) {  
        
        Logger logger = Logger.getLogger(Log4jLayout2.class);          
        SimpleLayout layout = new SimpleLayout();  
        //HTMLLayout  layout = new HTMLLayout();  
        FileAppender appender = null;  
        try  
        {  
            //把输出端配置到out.txt  
            appender = new FileAppender(layout,"d:\\out.txt",true);  
        }catch(Exception e)  
        {              
        }  
        logger.addAppender(appender);//添加输出端  
        //BasicConfigurator.configure();  
        logger.setLevel((Level)Level.ERROR);//覆盖配置文件中的级别  
        logger.debug("debug test");  
        logger.info("info");  
        logger.warn("warn");  
        logger.error("error");  
        logger.fatal("fatal");  
    }  
}

2、使用log4j.properties配置的自动日志方式,记录到本地日志和mysql数据库

log4j.properties如下:

log4j.rootLogger=INFO,appender2,logDB
#输出到文件 
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.File=log.log
log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
#将日志输出到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://123.2.1.1:3306/test
log4j.appender.logDB.User = root
log4j.appender.logDB.Password = ****
log4j.appender.logDB.Sql =INSERT INTO T_log4j(project_name,create_date,level,category,file_name,thread_name,line,all_category,message)values('Struts2','%d{yyyy-MM-dd HH:mm:ss}','%p','%c','%F','%t','%L','%l','%m') 

数据表创建

create table t_log4j(
  id int(11) NOT NULL auto_increment,
project_name varchar(100) null ,create_date  datetime null,level  varchar(10) null,category  varchar(100) null,file_name  varchar(100) null,thread_name  varchar(100) null,line int null,
all_category  varchar(100) null,message  varchar(100) null ,
  PRIMARY KEY  (id))

java程序代码如下:

package test;

import org.apache.log4j.*;

public class Log4jLayout {
    public static void main(String[] args) {  
        
        Logger logger = Logger.getLogger(Log4jLayout.class);          
        logger.debug("debug test");  
        logger.info("info");  
        logger.warn("warn");  
        logger.error("error");  
        logger.fatal("fatal");  
    }  
}

程序运行结果:



猜你喜欢

转载自blog.csdn.net/lqk1603/article/details/80168612