jdk1.4的logging的数据库handler实现源码

package com.benqguru.palau.log.jdk14log;

import java.util.logging.*;
import java.sql.*;

class JDBCHandler
extends Handler {

public void flush() {
}

public void publish(LogRecord record) {
Connection conn = null;

PreparedStatement pstmt = null;

try {
Driver d = (Driver) (Class.forName("org.gjt.mm.mysql.Driver").
newInstance());
DriverManager.registerDriver(d);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/logtest",
"root", "");
if (conn != null) {
Object[] content = record.getParameters();
String sql = "insert into MyLog(logTime,EventType) values(?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, record.getMillis());
pstmt.setString(2, (String) content[0]);
//save loginfo in databse
pstmt.execute();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

public void close() throws java.lang.SecurityException {

}

//测试方法
public static void main(String[] args) {
Logger log = Logger.getLogger(
"com.benqguru.commons.logging.test.JDBCHandler");
JDBCHandler jdbc = new JDBCHandler();
log.addHandler(jdbc);
String[] content = {
"insert"};
LogRecord lr = new LogRecord(Level.INFO, "second test message");
lr.setParameters(content);
// first insert log
log.log(Level.INFO, "first test message", content);
//second insert log
log.log(lr);
}
}

你可能感兴趣的:(sql,mysql,jdbc)