As we all know, log4j is an excellent open source logging project, we can not only customize the output of the log format, you can also define the destination of the log output, such as: screen, text files, databases, even through the socket output.
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.
We use Jdbcappender class directly into the log information into the database, in the log information needs to obtain user information, you can pass the filter request or Session object, from the session to get the user information how to spread to log4j. Log4j gives us the MDC (MDC is a very useful class for log4j, which stores contextual information for the application (context infomation), 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);
When configuring Patternlayout, use:%x{key} to output the corresponding value.
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.
Configure--->
Log4j.appender.db.sql=insert into LOG (logname,username,class,mothod,createtime,loglevel,msg) VALUES ('%X{userId} ', '%x{username} ', '%c ', '%m ', '%d{yyyy-mm-dd HH:mm:ss} ', '%p ', '%m '
which
%d output log point-in-time date or time, the default format is ISO8601, you can specify the format after, such as:%d{yyyy-mm-dd HH:mm:ss}, output similar: 2005-7-19 17:49:27, just fit to insert SQL Server;
%t the name of the thread that generated the log event;
%p log log_level, such as debug, warn, or info;
The class of the output of%c, usually the full name of the class in which it is located, such as "Inotes.default";
%m the contents of the log;
%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code. such as Write2database.main (WRITE2DATABASE.JAVA:33);
%n output a carriage return line feed, Windows platform "", Unix Platform ""