Log4J写系统日志到数据库

1. 建立存放日志的数据库表:

-- Create table
create table SYS_LOG
(
  ID          VARCHAR2(8) not null,
  MODEL       VARCHAR2(40) not null,
  USER_ID     VARCHAR2(8) not null,
  OPERATEION  VARCHAR2(200) not null,
  OPER_TIME   DATE not null,
  DESCRIPTION VARCHAR2(500)
)

2.配置log4j.properties文件,并放在src下:

log4j.rootLogger=INFO, stdout, jdbc  


#std appender  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  


#jdbc appender  这个是最主要的
log4j.appender.jdbc=com.supermap.earth.rims.syslog.JDBCAppender
log4j.appender.jdbc.driver=oracle.jdbc.driver.OracleDriver
log4j.appender.jdbc.url=jdbc:oracle:thin:@172.16.113.13:1522:earthdb
log4j.appender.jdbc.userName=earth_sys
log4j.appender.jdbc.password=123456
log4j.appender.jdbc.sql=insert into sys_log (id, model, user_id, operateion, oper_time, description)values  (?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?)

3.继承实现AppenderSkeleton :

package com.supermap.earth.rims.syslog;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class JDBCAppender extends AppenderSkeleton {
private String driver;
private String url;
private String userName;
private String password;
private String sql;
@Override
protected void append(LoggingEvent e) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(this.driver);
conn = DriverManager.getConnection(this.url, this.userName,
this.password);
if (e.getMessage() instanceof ParameterizedMessage) {
try {
pstmt = conn.prepareStatement(sql);
Object[] params = ((ParameterizedMessage) e.getMessage())
.getParameters();
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
pstmt.executeUpdate();
} catch (SQLException ex) {
this.errorHandler.error("log into database failed!", ex, 0);
} finally {
pstmt.close();
conn.close();
}
}
} catch (ClassNotFoundException ex) {
this.errorHandler.error("load jdbc driver [" + this.driver
+ "] failed!", ex, 0);
} catch (SQLException ex) {
this.errorHandler.error("establish connect failed!", ex, 0);
}
}
@Override
public void close() {
}


@Override
public boolean requiresLayout() {
return false;
}

public void setDriver(String driver) {
this.driver = driver;
}

public void setUrl(String url) {
this.url = url;
}

public void setUserName(String userName) {
this.userName = userName;
}

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

public void setSql(String sql) {
this.sql = sql;
}
}

4。定义接口JDBCLogMessage :

package com.supermap.earth.rims.syslog;
import java.util.Arrays;
public class JDBCLogMessage implements ParameterizedMessage {

private static final long serialVersionUID = 1709063421963292637L;

private Object[] params;


public JDBCLogMessage(Object... params) {


this.params = params;


}
public Object[] getParameters() {

   return this.params;
}

public Object getParameter(int index) throws IndexOutOfBoundsException {
    return this.params[index];
}

public int getParameterCount() {
    return this.params.length;
}

@Override
public String toString() {
    return Arrays.toString(this.params);
}
}


5。定义Loggers

package com.supermap.earth.rims.syslog;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.supermap.earth.rims.util.ReportModelUtil;

//Loggers.log("勘查报告", "123456789", "新增", "现场勘查报告");
public class Loggers {
public static void log(String model, String userId, String operation,
String description) {
String id = UUID.randomUUID().toString().replaceAll("-", "");
String operaTime = new Date().toLocaleString();
Logger logger = Logger.getRootLogger();
ParameterizedMessage msg = new JDBCLogMessage(id, model, userId,
operation, operaTime, description);
logger.info(msg);
}

public static void log(String tabName, String userId, String operation) {
String[] des = ReportModelUtil.getModel(tabName).split(";");
String id = UUID.randomUUID().toString().replaceAll("-", "");
String operaTime = new Date().toLocaleString();
Logger logger = Logger.getRootLogger();
ParameterizedMessage msg = new JDBCLogMessage(id, des[0], userId,
operation, operaTime, des[1]);
logger.info(msg);
}
}


6。定义ParameterizedMessage 接口:

package com.supermap.earth.rims.syslog;

import java.io.Serializable;

public interface ParameterizedMessage extends Serializable {

public Object[] getParameters();

public Object getParameter(int index) throws IndexOutOfBoundsException;


public int getParameterCount();
}
7.以上步骤已经完成,下面是测试代码:

public class Test {
public static void main(String[] args) {
Loggers.log("勘查报告", "123456789", "新增", "现场勘查报告");
}

}


你可能感兴趣的:(Java)