Log4j writes the log into the database

Source: Internet
Author: User
Tags log4j

Log4j is an excellent open source logging project, we can not only customize the format of the output log, but also define the destination of the log output, such as: screen, text file, database, even through the socket output. This section mainly describes how to enter log information into the database (you can insert any database, this is mainly to take MSSQL as an example).
Using log4j to write the log to the database is mainly used under the log4j package of the Jdbcappender class, which provides the ability to write log information asynchronously, we can directly use this class to write our log information to the database, or to extend the Jdbcappender class, is to use the Jdbcappender class as the base class. The following is an example of how log4j writes log information to the database.
Our requirements: In the process of software development, we need to record the debugging information, operation information and so on, so that the following audit, the log information includes user ID, user name, Operation class, Path, method, operation time, log information.
Design idea: We use the Jdbcappender class to insert log information directly into the database, all only need to configure this class on the configuration file can be, to obtain user information need to use filter to achieve, (if not need the user's information, do not need to design filters, in fact, most of the cases are the need for these user information , especially in Web application development) in the log information to obtain user information, through the filter request or Session object, from the session to get user information how to pass to log4j, log4j for us to provide the MDC (MDC is log4j kind of very useful classes, They are used to store contextual information (context infomation) for the application, making it easy to use these contextual information in log. The MDC internally uses a map-like mechanism to store information, and context information is stored separately by each thread, unlike information that is stored in "map" with their key values. The corresponding method,

Mdc.put (key, value); Mdc.remove (key); Mdc.get (key);

Use:%x{key} to output the corresponding value when Patternlayout is configured. With MDC, we can get the user information in the filter, then use the Mdc.put ("key") method, log in the execution of SQL statements through the%x{key} to output the corresponding value.


Implementation steps:
1, in your project to ensure that there are log4j and commons-logging these two jar files;
2, set the table structure for which you want to insert log information

if exists  (select * from dbo.sysobjects where id = object_id (N ' [ DBO]. [Wdzlog]  and objectproperty (id, n ' isusertable ')  = 1)    drop table  [DBO]. [wdzlog]   go      create table [dbo]. [wdzlog]  (       [WDZLOGID] [int] IDENTITY  (1, 1)   not null ,       [LogName] [varchar]  (255)  COLLATE  chinese_prc_ci_as null ,//User ID        [UserName] [varchar]  ( 255)  collate chinese_prc_ci_as null ,//user name        [class]  [varchar]  (255)  collate chinese_prc_ci_as null ,//class name         [Mothod] [varchar]  (255)  collate chinese_prc_ci_as null //, method name        &NBSP [createtime] [varchar]  (255)  collate chinese_prc_ci_as null ,//generation time        [LogLevel] [varchar]  ( collate chinese_prc_ci_as null)  ,//Log Level        [MSG] [varchar]  (555)  COLLATE CHINESE_PRC _ci_as null //log information   )  ON [PRIMARY]   go   if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id (N ' [dbo].[ Wdzlog] and OBJECTPROPERTY (ID, N ' isusertable ') = 1) drop table [dbo]. [Wdzlog] Go CREATE TABLE [dbo]. [Wdzlog] ([wdzlogid] [int] IDENTITY (1, 1) not NULL, [LogName] [varchar] (255) COLLATE chinese_prc_ci_as NULL,//user ID [UserName] [varchar] (255) COLLATE chinese_prc_ci_as NULL,//user name [class] [varchar] (255) COLLATE chinese_prc_ci_as NULL,//class name [Mothod] [varcha R] (255) COLLATE chinese_prc_ci_as null//, method name [createtime] [varchar] (255) COLLATE chinese_prc_ci_as NULL,//Generation time [Loglev EL] [varchar] (20)COLLATE chinese_prc_ci_as NULL,//log level [MSG] [varchar] (555) COLLATE chinese_prc_ci_as NULL/log information) on [PRIMARY] Go

3, the configuration file (excerpt from our project) will be explained in detail in this configuration file, it is also log4j the core part.
log4j.properties   log4j.rootlogger=info,stdout                   log4j.logger.org.springframework.web.servlet=info,db      log4j.logger.org.springframework.beans.factory.xml=info   Log4j.logger.com.neam.stum.user =info,db      log4j.appender.stdout=org.apache.log4j.consoleappender   log4j.appender.stdout.layout=org.apache.log4j.patternlayout   log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss} %p [%c] - -  <%m>%n      Log4j.appender.logfile=org.apache.log4j.dailyrollingfileappender    log4j.appender.logfile.file=${webapp.root}/web-inf/logs/exppower.log   log4j.appender.logfile.datepattern=.yyyy-mm-dd   log4j.appender.logfile.layout= org.apache.log4j.patternlayout   LOG4J.APPENDER.LOGFILE.LAYOUT.CONVERSIONPATTERN=%D&NBsp;%p [%c] wang- <%m>%n     ########################     # jdbc  Appender     #######################       #log4j logger.business=info,db   Log4j.appender.db=com.neam.commons.myjdbcappender    log4j.appender.db=jdbcextappender      log4j.appender.db.buffersize=10      log4j.appender.db.sqlname=log      log4j.appender.db.driver=net.sourceforge.jtds.jdbc.driver                              log4j.appender.db.url=jdbc:jtds:sqlserver://localhost:1433;databasename=pubs        log4j.appender.db.user=sa      log4j.appender.db.password=sa      log4j.appender.db.sql=insert into wdzlog  (logname,username,class,mothod,createtime,loglevel,msg )  values  ('%x{userid} ', '%x{username} ', '%c ', '%m ', '%d{yyyy-mm-dd hh:mm:ss} ', '%p ', '%m ')        log4j.appender.db.layout=org.apache.log4j.patternlayout   log4j.properties Log4j.rootLogger=INFO , stdout log4j.logger.org.springframework.web.servlet=info,db log4j.logger.org.springframework.beans.factory.xml= INFO log4j.logger.com.neam.stum.user=info,db Log4j.appender.stdout=org.apache.log4j.consoleappender Log4j.appender.stdout.layout=org.apache.log4j.patternlayout log4j.appender.stdout.layout.conversionpattern=%d{ YYYY-MM-DD HH:mm:ss}%p [%c]--<%m>%n Log4j.appender.logfile=org.apache.log4j.dailyrollingfileappender Log4j.appender.logfile.file=${webapp.root}/web-inf/logs/exppower.log log4j.appender.logfile.datepattern=. YYYY-MM-DD Log4j.appender.logfile.layout=org.apache.log4j.patternlayout log4j.appender.logfile.layout.conversionpattern=%d%p [%c] wang-<%m>%n ######################## # JDBC Appender ####################### #log4j. Logger.business=infO,db #log4j. Appender.db=com.neam.commons.myjdbcappender Log4j.appender.db=jdbcextappender log4j.appender.db.buffersize=10 Log4j.appender.db.sqlname=log log4j.appender.db.driver= Net.sourceforge.jtds.jdbc.Driver log4j.appender.db.url=jdbc:jtds:sqlserver://localhost:1433;databasename=pubs Log4j.appender.db.user=sa Log4j.appender.db.password=sa Log4j.appender.db.sql=insert into WDZLOG (LogName,UserName, CLASS,MOTHOD,CREATETIME,LOGLEVEL,MSG) VALUES ('%x{userid} ', '%x{username} ', '%c ', '%m ', '%d{yyyy-mm-dd HH:mm:ss} ', '% P ', '%m ') log4j.appender.db.layout=org.apache.log4j.patternlayout

4. Write the filter (Resfilter.java)
import java.io.ioexception;   import javax.servlet.filter;   import  javax.servlet.filterchain;   import javax.servlet.filterconfig;   import  javax.servlet.servletexception;   import javax.servlet.servletrequest;   import  javax.servlet.servletresponse;   import javax.servlet.http.httpservletrequest;   Import  javax.servlet.http.HttpSession;      import org.apache.log4j.logger;   import org.apache.log4j.mdc;      import com.neam.domain.user;       public class resfilter implements filter{                   private final static double default_userid = math.random () *100000.0;            public void  destroy () &NBsp {       }          public void  Dofilter (servletrequest request, servletresponse response,               filterchain chain)  throws IOException,  servletexception {          httpservletrequest req= ( HttpServletRequest) request;           HttpSession  Session= req.getsession ();           if  (session== NULL) {               mdc.put ("UserId"), Default_userid);             }            else{                user customer= (user) Session.getattribute ("user");                if  (customer==null) {                    mdc.put ("UserId", Default_userid);                    mdc.put ("UserName", Default_userid);               }                else                {                    mdc.put ("UserId", Customer.getname ());                   mdc.put (" UserName ", Customer.getname ());               }            }           // Logger.info ("TEST&NBSP;FOR&NBSP;MDC.");              chain.dofilter (request, response);        }       public void init ( Filterconfig config)  throws ServletException {  //      this.filterconfig = config;   //     string ccc = config.getservletcontext (). Getinitparameter ("Cherset");   //     this.targetencoding = config.getinitparameter ("Cherset") ;           }  }   import java.io.IOException; Import Javax.servlet.Filter; Import Javax. servlet. Filterchain; Import Javax.servlet.FilterConfig; Import javax.servlet.ServletException; Import Javax.servlet.ServletRequest; Import Javax.servlet.ServletResponse; Import Javax.servlet.http.HttpServletRequest; Import javax.servlet.http.HttpSession; Import Org.apache.log4j.Logger; Import Org.apache.log4j.MDC; Import Com.neam.domain.User; public class Resfilter implements filter{private final static double default_userid= math.random () *100000.0; Destroy () {} public void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) throws , servletexception {httpservletrequest req= (httpservletrequest) request; HttpSession session= req.getsession (); if (session==null) {mdc.put ("userId", Default_userid);} else{user customer= (user) Session.getattribute ("user"); if ( Customer==null) {mdc.put ("userId", Default_userid); Mdc.put ("UserName", Default_userid); else {mdc.put ("UserId", Customer.getname ()); Mdc.put ("UserName", Customer.getname ()); }}//loGger.info ("Test for MDC."); Chain.dofilter (request, response); public void init (Filterconfig Config) throws Servletexception {//this.filterconfig = Config;//String CCC = config.ge Tservletcontext (). Getinitparameter ("Cherset"); this.targetencoding = Config.getinitparameter ("Cherset"); } }

5, in the need to write to the log where the introduction

Private Log logger = Logfactory.getlog (This.getclass ());   The log Logger.info ("") can be written in a specific method;   Logger.debug ("");   Logger.warn ("");   Logger.error (""); Private Log logger = Logfactory.getlog (This.getclass ()); The log Logger.info ("") can be written in a specific method; Logger.debug (""); Logger.warn (""); Logger.error ("");

Detailed configuration file:
Log4j.properties
Log4j.properties
Log4j.rootlogger=info,stdout


//Configure root logger,Its syntax is:
Log4j.rootlogger = [level], appenderName1, appenderName2, ...
Level: Is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, if the info level is defined here, all debug-level log information in the application will not be printed.
Appendername: is to specify where the log information is exported. You can specify multiple output destinations at the same time.
For example: LOG4J.ROOTLOGGER=INFO,A1,B2,C3 configured 3 output places we can set to let A1 output in the console, B2 production log files, C3 let log information into the database.
In this example, all log information is printed on the console.
Log4j.logger.org.springframework.web.servlet=info,db
Sets the log information for some classes in the package under spring to the database and prints them on the console. DB is writing log information to the database (Log4j.rootlogger=info,stdout)
Log4j.logger.org.springframework.beans.factory.xml=info
In this example, to allow log information to be written to the database under certain packets
Log4j.logger.com.neam.stum.user=info,db
Set the log information under one of your modules to print on the console and save it to the database

The following is the configuration to print log information on the console, which is no longer described in detail here.
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%p [%c]--<%m>%n

The following is a configuration that writes log information to a file and is no longer described in detail here.
Log4j.appender.logfile=org.apache.log4j.dailyrollingfileappender
Log4j.appender.logfile.file=${webapp.root}/web-inf/logs/exppower.log
Log4j.appender.logfile.datepattern=.yyyy-mm-dd
Log4j.appender.logfile.layout=org.apache.log4j.patternlayout
log4j.appender.logfile.layout.conversionpattern=%d%p [%c] wang-<%m>%n

########################

# JDBC Appender

#######################


#log4j. Appender.db=com.neam.commons.myjdbcappender
The following is the configuration that inserts log information into the database.
Log4j.appender.db=org.apache.log4j.jdbc.jdbcappender
Configure the output target as a database (if you want to output the log in the console, configure it as Log4j.appender.) StdOut =org.apache.log4j.consoleappender, write log to file, configure to Log4j.appender.logfile= Org.apache.log4j.DailyRollingFileAppender
Such a configuration should be available in many places, and needs to be checked for information. Of course, you can also expand your own org.apache.log4j.jdbc.JDBCAppender this class, just need to configure here can be, for example, we configure my own extended Myjdbcappender, configured to #log4j.appender.db= Com.neam.commons.MyJDBCAppender

log4j.appender.db.buffersize=10
Set the cache size, that is, when there are 10 log information is to forget the database inserted once

Log4j.appender.db.driver=net.sourceforge.jtds.jdbc.driver
Set the driver to insert the log into the database
Log4j.appender.db.url=jdbc:jtds:sqlserver://localhost:1433;databasename=pubs

Log4j.appender.db.user=sa

Log4j.appender.db.password=sa

Log4j.appender.db.sql=insert into Wdzlog (logname,username,class,mothod,createtime,loglevel,msg) VALUES ('%X{userId } ', '%x{username} ', '%c ', '%m ', '%d{yyyy-mm-dd HH:mm:ss} ', '%p ', '%m '
Set the format and content of the log information to be inserted,%x{userid} is the key value in the MDC, because we put the user ID and user name in the MDC in the filter, where we can use%x{userid} and%x{username} Taking out the user's ID and user name; '%c ' indicates that the log information came from that class;%m indicates that the log information came from that method;%d{yyyy-mm-dd HH:mm:ss} represents the time that the log information was generated, {Yyyy-mm-dd HH:mm:ss} represents a time format , you can also write the level of log information directly%d;%p (debug info warn error);
%m indicates the log information you wrote
Log4j.appender.db.layout=org.apache.log4j.patternlayout

This article reprint Source: http://blog.csdn.net/ziruobing/article/details/3919501

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.