log4j Java Edition How to write a log to a database __ database

Source: Internet
Author: User
Tags log log throwable stringbuffer log4j

In fact, if it is directly through JDBC to connect to the database, then the following link

Http://www.dankomannhaupt.de/projects/index.html
Jdbcappender.zip has been able to easily implement this function,

But in reality, especially in large applications, the basic is through DataSource to get
Connection, and this zip has made it clear that it does not support DataSource, so what do we do?

I solve this, for the application of Java EE itself whether you use Spring+hibernate or c3p0 to get
Datasource, he eventually got the connection in JDBC to do database operations, and Jdbcappender
It is also through connection to manipulate the database, so the idea is that if you get the JDBC connection in your frame,
Then set him up in the Jdbcapplender.

With this in mind, I need to understand the code in Jdbcappender.zip to see if connection is placed in Jdbcappender

First, let's take a look at how this jdbcappender is integrated into log4j if the JDBC configuration is normal.
Here is the use of Jdbcappender

public class Log4jtest {
Create A category instance for this class
static Logger Logger = Logger.getlogger (Log4jtest.class);

public static void Main (string[] args) {


Jdbcappender ja = new Jdbcappender ();

Set options with Method SetOption ()
Ja.setconnector ("Org.apache.log4j.jdbcplus.examples.OracleConnectionHandler");
Ja.seturl ("jdbc:oracle:thin:@.");
Ja.setusername ("mex_pr_dev65");
Ja.setpassword ("mex_pr_dev65");

Ja.setsqlhandler ("Org.apache.log4j.jdbcplus.examples.SqlHandler");

Add the Appender to a category

Logger.addappender (JA);
Logger.debug ("Debug");


}
}
}

The class above is basically divided into so many parts
1. As with general log4j usage, get logger instance
2.new a Jdbcappender
3. Set up two-part parameters for JDBC, one for JDBC to establish the connection parameters, such as the URL, and other parts of the specific insert SQL handler (you can use handler to reflect the INSERT statement can also write SQL to the log4j configuration file, I use handler to process INSERT statements here)
4. Add the jdbcappender you just set up in logger instance
5. Complete

From the example above it seems to be unable to set connection, then view the Jdbcappender source found
Jdbcappender has Setconnectionhandler (interface Jdbcconnectionhandler ()) method;
You can use this method to put connection into the Jdbcappender, but you must implement the interface Dbcconnectionhandler

Interface Jdbcconnectionhandler as follows
Public interface Jdbcconnectionhandler {

/**
* Get a connection
*
* @return The Connection value
* @exception exception
* Description of Exception
*/
Connection getconnection () throws Exception;

/**
* Get a defined connection
*
* @param _url
* Description of Parameter
* @param _username
* Description of Parameter
* @param _password
* Description of Parameter
* @return The Connection value
* @exception exception
* Description of Exception
*/
Connection getconnection (String _url, String _username, String _password) throws Exception;
}

This time you found out we were looking for half a connection place that used to be here.

So I just need to implement the getconnection () method of this interface to put connection into Jdbcappender,

Now we build a handler, and the framework I use here is just Hibernate3

I need to get connecion from the hibernate3.

public class Cas2hibernateconnectionhandler implements Jdbcconnectionhandler {

Hibernate's session Factory
Sessionfactory SF = Hibernateconnection.getinstance ();

Public Connection getconnection () {
Connection con =null;
try {
con = sf.opensession (). connection ();

catch (Exception e) {
E.printstacktrace ();
}

return con;
}

Public Connection getconnection (string arg0, String arg1, String arg2)
Throws Exception {
TODO auto-generated Method Stub
return null;
}

}

This is my handler, in order to make the code more clear, I put my hibernateconnection also posted out, this is the common Sington pattern to get hibernate sessionfactory
public class Hibernateconnection {

private static sessionfactory sessionfactoryinstance = null;

Private Hibernateconnection () {
}

Unit Test.
Synchronized public static Sessionfactory getinstance () {

if (sessionfactoryinstance = = null) {
Configuration config;
try {
Config = new Configuration (). Configure (New File ("E://cas2//config//hibernate//hibernate.cfg.xml"));
Sessionfactoryinstance = Config.buildsessionfactory ();
catch (Hibernateexception e) {
E.printstacktrace ();
}
}

return sessionfactoryinstance;
}
}

Speaking of which, by the way, my frame here is hibernate3, and there are a lot of database-related frameworks like hibernate+spring or C3P0, and that doesn't make any sense.
Just find the appropriate way to get the JDBC connection, build your own Connectionhandler and implement the Getconnection ().

By this time the database connection is already available, then you need to write a specific INSERT statement, there are two ways, one is to write directly in the log4j configuration file
This configuration file can be XML, also can properties, this site also has a specific description of how to do so do not say;
The other is Ja.setsqlhandler ("Org.apache.log4j.jdbcplus.examples.SqlHandler");
You realize a sqlhandler, then set to Jdbcappender.

The newly built Sqlhander need to implement the interface
Public interface Jdbcsqlhandler {

/**
* Get a sql-statement.
* Return null or empty string if no should be logged.
*
* @return The SQL statement. Null If there is no to log.
* @exception exception
* Any Exception
*/
String getstatement (Loggingevent event) throws Exception;
}

There's only one way to getstatement, and it's okay to write a specific insert statement.

public class Casloginhandler implements Jdbcsqlhandler {

Private final int max_length_message = 3000;

Public String Getstatement (Loggingevent event) throws Exception {
Try {throw new Throwable ();} catch (Throwable th) {
Th.printstacktrace (); }
Locationinfo locinfo = Event.getlocationinformation ();
Throwableinformation throwableinfo = Event.getthrowableinformation ();
StringBuffer throwablestringbuffer = new StringBuffer ();
String locinfostring = "', ', ', ', '";

if (locinfo!= null) {
locinfostring = "'" + locinfo.getclassname () + "', '" + locinfo.getmethodname ()
+ "', '" + locinfo.getfilename () + "', '" + locinfo.getlinenumber () + "";
}
if (throwableinfo!= null) {
String[] lines = Throwableinfo.getthrowablestrrep ();
for (int index = 0; index < lines.length; index++) {
Throwablestringbuffer = (stringbuffer) throwablestringbuffer.append (Lines[index)
+ "/r/n");
}
}

StringBuffer sb = new StringBuffer ();
Sb.append ("Insert into Um_sys_log" (ID, Log_date, Log_level, LOGGER, OPERATOR, Application_name, Message_key, Log_message ) Values (");
Sb.append ("Seq_um_sys_log.nextval,");
Sb.append ("To_date");
Sb.append (DATEFORMATUTIL.FORMDATETOYYYYMMDD24) (New Date (Event.timestamp));
Sb.append ("', ' yyyy-dd-mm HH24:mi:SS ')");
Sb.append (", '");
Sb.append (Event.getlevel (). toString ());
Sb.append ("', '");
Sb.append (Event.getloggername ());
Sb.append ("', ' Bgao ', ' CAS2 ', ' Login sucess ', ' User Bgao loginsuccess ')");

return sb.tostring ();
}

}

This is the Casloginhandler I built.
And then set the handler to Jdbcappender.
Ja.setsqlhandler ("Com.bgao.log.CasLogHandler");


This completes the entire log log writing to the database. Of course, there are questions to think about, General Log.debug ("MSG"); This writing all log information is a MSG output
, such as "John in 127.0.0.1 machine query table XXX"; How to simply insert a sentence into a different field, There are many ways to think about which is more convenient and more concise.

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.