首先要引入可以写日志的jar log4j.jar
<!-- Log4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.0</version>
</dependency>
第一:写入log到指定位置
然后在resource目录中添加一个log4j.xml的文件(和jdbc.properties同一目录,目录可以随便配,这样配主要为了好读取文件)
<?xml version="1.0" encoding="utf-8"?>
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.RollingFileAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="code" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/mnt/shared/register/log/code/code.log" />//写日志的路径
<param name="DatePattern" value=".yyyy-MM-dd-HH-mm" />//格式化日期
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n" />
</layout>
</appender>
//从哪里开始写入日志,指定是在这个controller使用
<logger name="cp.pay.mj.action.UserController"
additivity="false">
<level value="INFO" />
//ref=code,就是跳转到上面 appender name=code方法,
//由此可见,要是写多个日志,需要配置不同的ref,说白了,就是把这两块代码多复制几遍,改个参数
<appender-ref ref="code" />
</logger>
</log4j:configuration>
在controller的使用
private Logger logger = Logger.getLogger(this.getClass());
需要什么样的格式可以自己去设置,目的就是为了读取log的时候,有统一的格式,好处理,我加了&就是为了读取的时候好拆分我的字符串
logger.info("spid="+spid.trim() + "&phone=" + phone.trim() + "&cpparam=" + cpparam.trim()+ "&createdate=" + sdf.format(new Date()));
如果你配置正确的话,就会在你的配置的目录中,生成一个log文件,并且内容也写进去了
第二:从目录中读取log,并进行相应的业务处理
如果你想定时比如每隔多长时间读取一次log,这肯定就要用到定时器,如果不需要,
首先在web.xml中添加配置
<listener-class>cp.pay.mj.utils.CpScRequestLogTODatabase</listener-class>
</listener>
CpScRequestLogTODatabase这个类就是处理读取log的关键,名字自己命名
package cp.pay.mj.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
public class CpScRequestLogTODatabase implements ServletContextListener{//定时处理业务
public static String QUO_LOGS_PAR="/mnt/shared/register/log/code";//读取的目录路径
public static String INSERT_INTO_TBSP = "insert into tbsp(spid,phone,cpparam,status,createdate,cpid) values(?,?,?,?,?,?);";//执行的业务逻辑
public static String UPDATE_TBSP="";
public static String REGEX = "(:INFO)|( - )|=|&";
public static String endString = "";
boolean mo=false;
private Timer timer;//定时器
private Logger logger = Logger.getLogger(this.getClass());
public void saveTBSPToDatebase(File[] files){
List<Map<String,String>> listSubmits=new ArrayList<Map<String,String>>();
for(File file:files){
if( file.exists() ){
List<Map<String,String>> listSubmit =ReadLogs(file);
if(listSubmit!=null&&listSubmit.size()!=0)
listSubmits.addAll(listSubmit);
}
}
if(listSubmits.size()!=0){
try{
mo = JdbcUtil.getInstance().executeCpRequestErr(INSERT_INTO_TBSP, listSubmits);
}catch (Exception E){
E.printStackTrace();
}
}
delete(files);//读取后删除文件
}
public void delete(File[] files){
if(mo==true){
for(File file:files){
if( file.exists() ){
System.out.println("deleteErr"+file.delete());
}
}
}
}
public List<Map<String,String>> ReadLogs(File file){
List<Map<String,String>> logsList= new ArrayList<Map<String,String>>();
BufferedReader reader = null;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
reader = new BufferedReader(isr);
String tempString =null;
while((tempString = reader.readLine()) != null){
Map<String,String> map = spiltString(tempString,REGEX);
if(map!=null){
logsList.add(map);
}
}
isr.close();
return logsList;
} catch (FileNotFoundException e) {
logger.error(e);
return null;
} catch (IOException e) {
logger.error(e);
return null;
}
}
public static String readLastLine(File file, String charset) throws IOException {
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null;
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "r");
long len = raf.length();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == ' ') {
raf.seek(pos+1);
break;
}
}
if (pos == 0) {
raf.seek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
if (charset == null) {
return new String(bytes);
} else {
return new String(bytes, charset);
}
}
} catch (FileNotFoundException e) {
} finally {
if (raf != null) {
try {
raf.close();
} catch (Exception e2) {
}
}
}
return null;
}
public Map<String,String> spiltString(String tempString,String regex){
// System.out.println(tempString+"=============");
if(!tempString.contains("=")&&!tempString.contains("&")&&!tempString.contains(" - ")){return null;}
Map<String,String> map = new HashMap<String, String>();
String[] temps=tempString.split(regex);
map.put("date", temps[0]);
for(int i=2;i<=temps.length-2;i+=2){
map.put(temps[i], temps[i+1]);
}
// System.out.println(map+"--------");
return map;
}
public File[] choseFile(final String str){
File file = new File(QUO_LOGS_PAR);
File[] files=null;
if(file.exists()&&file.isDirectory()){
files=file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
if(filename.startsWith(str))
return true;
else
return false;
}
});
}
return files;
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
System.out.println("startTimerCpScre");
goTimer();
} catch (Exception e) {
goTimer();
logger.error(e);
}
}
private void goTimer() {
timer = new Timer();//定时器开始
timer.schedule( new TimerTask() {
@Override
public void run() {
try{
File[] filesQuo=choseFile("code.log.");
if(filesQuo!=null&&filesQuo.length!=0)
saveTBSPToDatebase(filesQuo);
}catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 1*1000*60*3);//每隔三分钟读取一次
}
}
package cp.pay.mj.utils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.log4j.Logger;
/**
*
*/
public class JdbcUtil {
private static MemCachedTest memCached = MemCachedTest.getInstance();
private static String filePath = "jdbc.properties";
private static JdbcUtil instance = null;
private static Logger logger = Logger.getLogger(JdbcUtil.class.getName());
public JdbcUtil() {
super();
}
public static JdbcUtil getInstance() {
if (instance == null) {
synchronized (JdbcUtil.class) {
if (instance == null) {
instance = new JdbcUtil();
}
}
}
return instance;
}
public static Properties readPropertiesFile(){
String realFilePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+filePath;
Properties pros = new Properties();
try {
InputStream is = new BufferedInputStream(new FileInputStream(realFilePath));
pros.load(is);
} catch (Exception e) {
logger.error(e);
}
return pros;
}
static{
Properties pros = readPropertiesFile();
String className = (String) pros.get("className");
try {
Class.forName(className).newInstance();
} catch (Exception e) {
logger.error(e);
}
}
public Connection getConnection(){
Properties pros = readPropertiesFile();
String url = (String) pros.get("url");
String user = (String) pros.get("user");
String password = (String) pros.get("password");
Connection conn = null;
try {
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
logger.error("获取连接",e);
}
return conn;
}
public Connection getConnections(){
Properties pros = readPropertiesFile();
String url = (String) pros.get("url1");
String user = (String) pros.get("user1");
String password = (String) pros.get("password1");
Connection conn = null;
try {
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
logger.error("获取连接",e);
}
return conn;
}
public void close(ResultSet rs,Statement st,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
logger.error("关闭连接",e);
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
logger.error("st连接",e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
logger.error("conn连接",e);
}
}
}
public void execute(String sql) {
JdbcUtil jbpu = getInstance();
Connection conn = null;
PreparedStatement pst = null;
try {
conn = jbpu.getConnection();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.executeUpdate();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
logger.error("插入渠道rollback error----------------");
}
} finally{
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
}
ResultSet rs = null;
jbpu.close(rs, pst, conn);
}
}
public void executes(String sql) {
JdbcUtil jbpu = getInstance();
Connection conn = null;
PreparedStatement pst = null;
try {
conn = jbpu.getConnections();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.executeUpdate();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
logger.error("插入渠道rollback error----------------");
}
} finally{
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
}
ResultSet rs = null;
jbpu.close(rs, pst, conn);
}
}
public boolean checkMoParms(Map<String,String> params){
if(params.get("chid")!=null&&
params.get("distro")!=null&¶ms.get("carrier")!=null&¶ms.get("appid")!=null){
String imei = params.get("imei");
if(imei!=null&&imei.length()>32)
params.put("imei", imei.trim().substring(0,32));
if(params.get("pkg")!=null&¶ms.get("pkg").length()>15){
params.put("pkg", params.get("pkg").trim().substring(0,15));
}
return true;
}
return false;
}
@SuppressWarnings("finally")
public boolean executeTip(String sql,Map<String,String> params) {
JdbcUtil jbpu = getInstance();
Connection conn = null;
boolean flag = true;
PreparedStatement pst = null;
try {
conn = jbpu.getConnection();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
int count=0;
for(String entry : params.keySet()){
count++;
pst.setString(1,entry.split(",")[0]);
pst.setString(2, entry.split(",")[1]);
pst.addBatch();
if(count%50==0) pst.executeBatch();
}
pst.executeBatch();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
flag =false;
} catch (SQLException e1) {
e1.printStackTrace();
logger.error("插入TipMap数据:",e);
}
e.printStackTrace();
} finally{
ResultSet rs = null;
jbpu.close(rs, pst, conn);
return flag;
}
}
public void executeUpdateID(String sql,List<String> params) {
JdbcUtil jbpu = getInstance();
Connection conn = null;
PreparedStatement pst = null;
try {
conn = jbpu.getConnection();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
int count=0;
for(String string:params){
count++;
pst.setString(1, string);
pst.addBatch();
if(count%200==0) pst.executeBatch();
}
pst.executeBatch();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
logger.error("插入数据:",e);
}
e.printStackTrace();
} finally{
ResultSet rs = null;
jbpu.close(rs, pst, conn);
}
}
public boolean executeCpRequestErr(String sql,List<Map<String,String>> params) {
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
JdbcUtil jbpu = getInstance();
Connection conn = null;
Connection conns = null;
boolean flag = false;
PreparedStatement pst = null;
PreparedStatement psts = null;
try {
conn = jbpu.getConnection();
conns = jbpu.getConnections();
conn.setAutoCommit(false);
conns.setAutoCommit(false);
pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
psts = conns.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
int count=0;
for(Map<String,String> param:params){
if("cpdf".equals(param.get("cpid"))){
psts.setString(1,param.get("spid"));
System.out.println(param.get("spid"));
psts.setString(2, param.get("phone"));
psts.setString(3, param.get("cpparam"));
psts.setString(4, "1");
psts.setString(5, param.get("date"));
psts.setString(6, param.get("cpid"));
psts.addBatch();
psts.executeBatch();
}else{
pst.setString(1,param.get("spid"));
System.out.println(param.get("spid"));
pst.setString(2, param.get("phone"));
pst.setString(3, param.get("cpparam"));
pst.setString(4, "1");
pst.setString(5, param.get("date"));
pst.setString(6, param.get("cpid"));
pst.addBatch();
pst.executeBatch();
}
memCached
.set(param.get("phone"), 0, "{"spid":""+param.get("spid")+"","phone":""+param.get("phone")+"","cpparam":""+param.get("cpparam")+""}");
}
System.out.println("000");
System.out.println(pst.toString());
conn.commit();
conns.commit();
flag = true;
System.out.println("1111");
} catch (Exception e) {
e.printStackTrace();
logger.error("插入数据:",e);
conn.rollback();
conns.rollback();
e.printStackTrace();
} finally{
try {
conn.setAutoCommit(true);
conns.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs = null;
jbpu.close(rs, pst, conn);
jbpu.close(rs, psts, conns);
return flag;
}
}
}
重启tomcat就可以看到写入读取log日志了