log4j.rootLogger=INFO,appender1,appender2,DATABASE# consolelog4j.appender.appender1=org.apache.log4j.ConsoleAppenderlog4j.appender.appender1.layout=org.apache.log4j.PatternLayoutlog4j.appender.appender1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n# filelog4j.appender.appender2=org.apache.log4j.FileAppenderlog4j.appender.appender2.File=log.loglog4j.appender.appender2.layout=org.apache.log4j.PatternLayoutlog4j.appender.appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n#mysql dbappender testlog4j.appender.DATABASE.driver=com.mysql.jdbc.Driverlog4j.appender.DATABASE.URL=jdbc:mysql://127.0.0.1:3306/LOG4Jlog4j.appender.DATABASE.username=rootlog4j.appender.DATABASE.password=rootlog4j.appender.DATABASE=control.DbAppenderlog4j.appender.DATABASE.layout=org.apache.log4j.PatternLayoutlog4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n %L
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);}@Overrideprotected 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!");}@Overrideprotected Connection getConnection() throws SQLException {// TODO Auto-generated method stub// return super.getConnection();if (connection == null) {connection = JdbcUtils.getConnection();}return connection;}@Overrideprotected 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_***))) == 1 ? "F": "M") + "','" + hm.get(HashMapping.STUDENT_TIME)+ "')";System.out.println(sql);return sql + hm.get("beanname");}return sql;}}
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_*** = "***";public static final String STUDENT_TIME = "time";}package bean;public class Students {private String name;private int age;private int ***;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 get***() {return ***;}public void set***(int ***) {this.*** = ***;}}//===============================================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;}}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 ***) {st = new Students();st.setName(name);st.setAge(age);st.set***(***);return st;}// bean key-valuepublic 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("***", st.get***());ht.put("time", sf.format(new Date()));ht.put("beanname","Students");}logger.info(ht);}}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 blocke.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 blocke.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 blocke.printStackTrace();} finally {try {istream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}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 blockSystem.out.println("insert fail!");} finally {if (sm != null) {try {sm.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}JdbcUtils.close(conn);}return flag;}public static String insertSql() {return "INSERT INTO StudentMessage(Name,Age,***,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 blockSystem.out.println("insert fail!");} finally {if (sm != null) {try {sm.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}JdbcUtils.close(conn);}return flag;}public static String insertSql(){return "INSERT INTO LogMessage(Time,Note,Username,Password) values(";}}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("TIBCO-VANCEINFO", "TIBCO-12345");go.getMethod(ub);// Students st = go.insertInfo("TIBCO", 21, 2);// go.getMethod(st);} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
09-17 07:50