博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
写log日志,并读取log日志
阅读量:5286 次
发布时间:2019-06-14

本文共 15375 字,大约阅读时间需要 51 分钟。

首先要引入可以写日志的jar  log4j.jar

org.slf4j
slf4j-api
1.6.0
org.slf4j
slf4j-log4j12
1.6.0
第一:写入log到指定位置 然后在resource目录中添加一个log4j.xml的文件(和jdbc.properties同一目录,目录可以随便配,这样配主要为了好读取文件)
//写日志的路径
//格式化日期
  //从哪里开始写入日志,指定是在这个controller使用
  //ref=code,就是跳转到上面 appender name=code方法,   //由此可见,要是写多个日志,需要配置不同的ref,说白了,就是把这两块代码多复制几遍,改个参数
在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中添加配置
cp.pay.mj.utils.CpScRequestLogTODatabase
 
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
> listSubmits=new ArrayList
>(); for(File file:files){
if( file.exists() ){
List
> 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
> ReadLogs(File file){ List
> logsList= new ArrayList
>(); 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
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() == '\n') { 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
spiltString(String tempString,String regex){ // System.out.println(tempString+"============="); if(!tempString.contains("=")&&!tempString.contains("&")&&!tempString.contains(" - ")){return null;} Map
map = new HashMap
(); 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
params){
if(params.get("chid")!=null&& params.get("distro")!=null&&params.get("carrier")!=null&&params.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&&params.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
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
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
> 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
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日志了

转载于:https://www.cnblogs.com/foreverstudy/p/10442233.html

你可能感兴趣的文章
OMG: daily scrum nine
查看>>
redis与spring结合错误情况
查看>>
第六章 字节码执行方式--解释执行和JIT
查看>>
字符串方法title()、istitle()
查看>>
yield语句
查看>>
查看linux系统中占用cpu最高的语句
查看>>
[洛谷P1738]洛谷的文件夹
查看>>
ubuntu server设置时区和更新时间
查看>>
【京东咚咚架构演进】-- 好文收藏
查看>>
【HTML】网页中如何让DIV在网页滚动到特定位置时出现
查看>>
文件序列化
查看>>
jQuery之end()和pushStack()
查看>>
Bootstrap--响应式导航条布局
查看>>
Learning Python 009 dict(字典)和 set
查看>>
JavaScript中随着鼠标拖拽而移动的块
查看>>
HDU 1021 一道水题
查看>>
The operation couldn’t be completed. (LaunchServicesError error 0.)
查看>>
php每天一题:strlen()与mb_strlen()的作用分别是什么
查看>>
工作中收集JSCRIPT代码之(下拉框篇)
查看>>
《转载》POI导出excel日期格式
查看>>