log4j 数据库 flushbuffer

在log4j中,可以用JDBCAppender将log的内容存贮到数据库中.但是,只能将内容整体放到数据库的一个字段中,如果想将log的内容分开来存贮到不同的字段中,就要对JDBCAppender重写做扩展了.这几天看了一下log4j的源码.做了一下简单的扩展.

例如;想将聊天记录的log存到数据库中,要将聊天记录的相关信息.fromid,toid,fromname,toname,time,content分开来,存到数据库中的不同字段时,将要怎么做呢. 可以继承JDBCAppender,对方法flushBuffer重写.如下;

import org.apache.log4j.jdbc.JDBCAppender;
import java.util.Iterator;
import java.sql.SQLException;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Element;
import java.util.Map;
import java.util.HashMap;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

public class ChatSaveAppender extends JDBCAppender {
    public void flushBuffer() {
        //Do the actual logging
        removes.ensureCapacity(buffer.size());
        for (Iterator i = buffer.iterator(); i.hasNext(); ) {
            try {
                LoggingEvent logEvent = (LoggingEvent) i.next();
                Object obj = logEvent.getMessage();
                String msg = obj.toString();
                System.out.println(msg);

//例如log是与xml文件输出的。格式如;<hi toname="小猫" cmd="msg" time="2007-5-21 00:00:41" fromid="2871146" toid="2534882" content="您好" status="0" fromname="小猪"/>
                Map<String,String> map = xmlToMap(msg);//将xml解析成map
                if(map!=null){
                    String fromid = "";
                    String fromname = "";
                    String toid = "";
                    String toname = "";
                    String content ="";
                    String time = "";
                    String status = "";
                    if(map.containsKey("fromid")){
                        fromid = map.get("fromid");
                    }

                    if(map.containsKey("fromname")){
                        fromname = ""+ map.get("fromname");
                    }
                    if(map.containsKey("toid")){
                        toid = ""+ map.get("toid");
                    }
                    if(map.containsKey("toname")){
                        toname = ""+ map.get("toname");
                    }
                    if(map.containsKey("content")){
                        content = ""+ map.get("content");
                    }
                    if(map.containsKey("status")){
                        status = ""+ map.get("status");
                    }
                    if(map.containsKey("time")){
                        time = ""+ map.get("time");
                    }
                    String sql = "insert into CHAT_LOG (FROMID,FROMNAME,TOID,TONAME,CONTENT,TIME,STATUS) values ("
                                 +fromid+",'"+fromname+"',"+toid+",'"+toname+"','" + content
                                 + "',to_date('"+time+"','yyyy-mm-dd hh24-mi-ss'),"+status+")";
                    execute(sql);
                }
                removes.add(logEvent);
            } catch (SQLException e) {
                errorHandler.error("Failed to excute sql", e,
                                   ErrorCode.FLUSH_FAILURE);
            }
        }
        // remove from the buffer any events that were reported
        buffer.removeAll(removes);
        // clear the buffer of reported events
        removes.clear();
    }

//下面解析log,由xml解析成map,用dom4j.
    public Map<String, String> xmlToMap(String parameters) {
        Map map =null;
            if (parameters != null && parameters.indexOf(CMD_NAME)>0 ) {
                    try {
                            Document document = DocumentHelper.parseText(parameters);
                            if (document != null) {
                                    Element root = document.getRootElement();
                                    if (root != null && root.getName().equalsIgnoreCase(ROOT_NAME)) {
                                         map = attributeToMap(root);
                                         root = null;
                                    }
                            }
                            document = null;
                    } catch (Exception e) {
                        System.out.println("format String:\n"+parameters + e);
                    } finally {
                            parameters = null;
                    }
            }
            return map;
    }


    public Map<String, String> attributeToMap(Element root) {
            List<Attribute> attributes = root.attributes();
            Map<String, String> map = new HashMap<String, String>(5);
            for (Attribute attribute : attributes) {
                    map.put(attribute.getName(), attribute.getText());
            }
            attributes = null;
            root = null;
            return map;
    }
}

log4j.properties文件可以写成如下;

log4j.rootLogger=DEBUG, DATABASE

log4j.appender.DATABASE = com.logsave.ChatSaveAppender
log4j.appender.DATABASE.Driver = oracle.jdbc.driver.OracleDriver
log4j.appender.DATABASE.URL = jdbc:oracle:thin:@127.0.0.1:1521:orc2
log4j.appender.DATABASE.User = myuser
log4j.appender.DATABASE.Password = mypassword
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=%m

也可以在程序中引用;

        ChatSaveAppender chatAppender = new ChatSaveAppender();
        chatAppender.setUser("myuser");
        chatAppender.setPassword("marryfive");
        chatAppender.setDriver("oracle.jdbc.driver.OracleDriver");
        chatAppender.setURL("jdbc:oracle:thin:@192.168.0.213:1521:orc2");
        org.apache.log4j.PatternLayout layout  = new PatternLayout();
        layout.setConversionPattern("%m");
        chatAppender.setLayout(layout);
        logger.addAppender(chatAppender);

你可能感兴趣的:(apache,oracle,sql,log4j,jdbc)