log4j+JDBC+mySQL 將物件寫入資料庫

iteye_4663發表於2012-03-20

    一、寫前嘮叨

      最近寫了一個關於將物件通過log4j的形式儲存到資料庫的例子,因對這個log4j正在入門,所以做之前查過很多資料,不過網上的資訊比較簡單,如下:

    1.所有資訊幾乎全部在配置檔案中進行獲取,如:資料庫相關的連線、使用者名稱、密碼、sql語句;日誌相關的appender、輸出、格式化、引數;

    2.寫到資料庫中的僅是一個字串而不是一個物件,如:將一個物件本身以及它的各個資料作為一條記錄存到資料庫

    3.程式碼的靈活性較低,如:只能存比較簡單的資料型別,如儲存一個物件及屬性的話,就不太容易做了。

  當然,網上的這些資料當然是為了最基礎的入門而做的,因此簡單了些,但也不乏比較深奧的資料,比如穿件連線池,考慮快取等等。。

   二、我的做法

     1.通過繼承JDBCAppender實現日誌的寫入的

     2.通過JDBC連線資料庫(也可通過HIBERNATE)

     3.資料庫和log4j的基本資訊配置到properties中,但資料庫可以自由選擇多種資料庫(在配置檔案中配置即可)

     4.將物件的屬性存到庫中

   三、專案例子

     1.專案結構圖:見附件,專案結構圖.png

     2. 資料庫:MYSQL  庫名:LOG4J  表名:LogMessage/StudentMessage

         表結構請看附件:LogMessage.png/StudentMessage.png

     3.程式碼及說明

     log4j.properties :分別輸出指定為:控制檯、檔案(log.log)、資料庫

 

log4j.rootLogger=INFO,appender1,appender2,DATABASE

# console
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.appender1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n

# file
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 dbappender test
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
log4j.appender.DATABASE.URL=jdbc:mysql://127.0.0.1:3306/LOG4J
log4j.appender.DATABASE.username=root
log4j.appender.DATABASE.password=root
log4j.appender.DATABASE=control.DbAppender
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n %L

    Conorl包——DbAppender.java :日誌提交中轉站,提取日誌資訊,處理後進行資料庫操作插入對應的表中

 

package control;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;

import bean.HashMapping;
import bean.Students;
import bean.UserBean;

import dao.JdbcUtils;
import dao.StudentsUtil;
import dao.UserUtil;

public class DbAppender extends JDBCAppender {

	protected void closeConnection(Connection con) {
		// TODO Auto-generated method stub
		// super.closeConnection(con);
		JdbcUtils.close(con);

	}

	@Override
	protected void execute(String sql) throws SQLException {
		// TODO Auto-generated method stub
		// super.execute(arg0);
		int flag = 0;
		int end = sql.lastIndexOf(")");
		String sqls = sql.substring(0, end + 1);
		String beanname = sql.substring(end + 1);
		if (beanname.equals("UserBean")) {
			 flag = UserUtil.insertUser(sqls);
		} else if (beanname.equals("Students")) {
			 flag = StudentsUtil.insertStudent(sqls);
		}
		System.out.println(flag == 0 ? "insert fail!" : "insert successful!");
	}

	@Override
	protected Connection getConnection() throws SQLException {
		// TODO Auto-generated method stub
		// return super.getConnection();
		if (connection == null) {
			connection = JdbcUtils.getConnection();
		}
		return connection;
	}

	@Override
	protected String getLogStatement(LoggingEvent event) {
		// TODO Auto-generated method stub
		// return super.getLogStatement(event);
		StringBuffer sbuf = new StringBuffer();
		Hashtable hm = (Hashtable) event.getMessage();
		String sql = null;
		if ((hm.get("beanname")).equals("UserBean")) {
			sbuf.append(UserUtil.insertSql());
			sql = sbuf.toString();
			int end = sql.lastIndexOf("(");
			sql = sql.substring(0, end) + "('" + hm.get(HashMapping.USER_TIME)
					+ "','" + event.getMessage() + "','"
					+ hm.get(HashMapping.USER_USERNAME) + "','"
					+ hm.get(HashMapping.USER_PASSWORD) + "')";
			System.out.println(sql);
			return sql + hm.get("beanname");
		} else if ((hm.get("beanname")).equals("Students")) {
			sbuf.append(StudentsUtil.insertSql());
			sql = sbuf.toString();
			int end = sql.lastIndexOf("(");
			sql = sql.substring(0, end)
					+ "('"
					+ hm.get(HashMapping.STUDENT_NAME)
					+ "','"
					+ hm.get(HashMapping.STUDENT_AGE)
					+ "','"
					+ (((Integer) (hm.get(HashMapping.STUDENT_SEX))) == 1 ? "F"
							: "M") + "','" + hm.get(HashMapping.STUDENT_TIME)
					+ "')";
			System.out.println(sql);
			return sql + hm.get("beanname");
		}
		return sql;

	}

}

    Bean包中的類——HashMapping.java :將屬性設定成常量(即鍵-值對中的鍵),便於程式碼中進行鍵值對的讀取。

 

package bean;

public class HashMapping {

	public static final String USER_USERNAME = "username";
	public static final String USER_PASSWORD = "password";
	public static final String USER_TIME = "time";
	
	public static final String STUDENT_NAME = "name";
	public static final String STUDENT_AGE = "age";
	public static final String STUDENT_SEX = "sex";
	public static final String STUDENT_TIME = "time";
}

   Bean包中的類——UserBean.java/Students.java: 對LogMessage/studentMessage表及此物件持久化

 

package bean;

public class Students {

	private String name;
	private int age;
	private int sex;
	private String time;

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

}
//===============================================
package bean;

import java.sql.Date;

public class UserBean {

	private String username;
	private String password;
	private String Time;
	private String Note;

	public String getTime() {
		return Time;
	}

	public void setTime(String time) {
		Time = time;
	}

	public String getNote() {
		return Note;
	}

	public void setNote(String note) {
		Note = note;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 Dao中的包——GetObject.java: 將物件放到hashtable中併傳送到dbappender中

 

package dao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import test.Test;

import bean.Students;
import bean.UserBean;

public class GetObject {
	private Logger logger = Logger.getLogger(GetObject.class);
	private UserBean ub;
	private Students st;
	private SimpleDateFormat sf;

	// 儲存物件
	public UserBean insertInfo(String username, String password) {

		ub = new UserBean();
		ub.setUsername(username);
		ub.setPassword(password);
		return ub;

	}

	public Logger getLogger() {
		return logger;
	}

	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	public UserBean getUb() {
		return ub;
	}

	public void setUb(UserBean ub) {
		this.ub = ub;
	}

	public Students getSt() {
		return st;
	}

	public void setSt(Students st) {
		this.st = st;
	}

	public SimpleDateFormat getSf() {
		return sf;
	}

	public void setSf(SimpleDateFormat sf) {
		this.sf = sf;
	}

	public Students insertInfo(String name, int age, int sex) {
		st = new Students();
		st.setName(name);
		st.setAge(age);
		st.setSex(sex);
		return st;
	}

	// bean key-value
	public void getMethod(Object obj) {

		sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		PropertyConfigurator.configure("log4j.properties");
		Hashtable ht = new Hashtable();
		ht.clear();
		if (obj instanceof UserBean) {
			ht.put("username", ub.getUsername());
			ht.put("password", ub.getPassword());
			ht.put("time", sf.format(new Date()));
			ht.put("beanname", "UserBean");
		} else if (obj instanceof Students) {
			ht.put("name", st.getName());
			ht.put("age", st.getAge());
			ht.put("sex", st.getSex());
			ht.put("time", sf.format(new Date()));
			ht.put("beanname","Students");
		}
		logger.info(ht);

	}

}

 Dao中的包——JdbcUtils.java: 資料庫的動態連結

 

package dao;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public final class JdbcUtils {
	//
	private static String url = null;
	private static String driver = null;
	private static String username = null;
	private static String password = null;

	private JdbcUtils() {

	}
	static{
		try {
			getProperties();
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException  {
		
		return DriverManager.getConnection(url, username, password);
	}

	public static void close(Connection conn) {

		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void getProperties() {

		Properties props = new Properties();
		FileInputStream istream = null;
		try {
			istream = new FileInputStream("log4j.properties");
			props.load(istream);
			Set s = props.keySet();
			Iterator it = s.iterator();
			while (it.hasNext()) {
				String id = (String) it.next();
				String value = props.getProperty(id);
				if(id.equals("log4j.appender.DATABASE.driver")){
					driver = value;
				}else if(id.equals("log4j.appender.DATABASE.URL")){
					url = value;
				}else if(id.equals("log4j.appender.DATABASE.username")){
					username = value;
				}else if(id.equals("log4j.appender.DATABASE.password")){
					password = value;
				}
//				System.out.println(id + ":=" + value);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				istream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

 Dao中的包——StudentsUtil.java/UserUtil.java: 對各自的表進行資料庫的操作

 

package dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class StudentsUtil {
	
	public static int insertStudent(String sql) {

		Connection conn = null;
		Statement sm = null;

		int flag = 0;

		try {
			conn = JdbcUtils.getConnection();
			sm = conn.createStatement();
			sm.execute(sql);
			flag = 1;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("insert fail!");
		} finally {
			if (sm != null) {
				try {
					sm.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			JdbcUtils.close(conn);
			
		}

		return flag;

	}

	public static String insertSql() {
		return "INSERT INTO StudentMessage(Name,Age,Sex,Time) values(";
	}
}
//===============================================
package dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import bean.UserBean;

public class UserUtil {

	public static int insertUser(String sql) {

		Connection conn = null;
		Statement sm = null;

		int flag = 0;

		try {
			conn = JdbcUtils.getConnection();
			sm = conn.createStatement();
			sm.execute(sql);
			flag = 1;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("insert fail!");
		} finally {
			if (sm != null) {
				try {
					sm.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			JdbcUtils.close(conn);
			
		}

		return flag;

	}
	public static String insertSql(){
		return "INSERT INTO LogMessage(Time,Note,Username,Password) values(";
	}

}
 

   test包——test.java :測試類

 

package test;

import java.lang.reflect.InvocationTargetException;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.jdbc.JDBCAppender;
import org.omg.CORBA.Request;

import dao.GetObject;

import bean.Students;
import bean.UserBean;

public class Test {

	public static void main(String[] args) {

		Test dbt = new Test();
		dbt.testUser();

	}

	public void testUser() {
		try {
			GetObject go = new GetObject();
			UserBean ub = go.insertInfo("EE-YY", "YY-12345");
			go.getMethod(ub);
			// Students st = go.insertInfo("YY", 21, 2);
			// go.getMethod(st);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

 結果見附加:stuM.png/logM.png

 

 

 

相關文章