【Log】一个写Log的类,留作备份

import  java.io. * ;
import  java.util. * ;
import  java.io.IOException;
import  java.text.SimpleDateFormat;
import  javax.servlet.http.HttpServletRequest;
public   class  BaseLog  {
 
private int retryCount = 3;
 
private static final int RETRY_INTERVAL = 300;
 
private SimpleDateFormat logTimeStamp = new SimpleDateFormat(
   
"yyyy-MM-dd HH:mm:ss:SSS");
 
private boolean writeTimeStamp = true;
 
private String path = null;
 
private PrintWriter writer = null;
 
private long logFileSize = 1048576L// 1MB
 private int fileBackTime = 0;
 
private boolean autoFlush = true;
 
public static String URI = "";
 
public BaseLog(String path, String fileSize, String fileBackTime)
   
throws IOException {
  
this(path, true, fileSize, fileBackTime);
 }

 
public BaseLog(String path, boolean autoFlush, String fileSize,
   String fileBackTime) 
throws IOException {
  
this.path = path;
  
this.autoFlush = autoFlush;
  
this.logFileSize = Integer.parseInt(fileSize) * 1048576L;
  
this.fileBackTime = Integer.parseInt(fileBackTime);
  
if (!autoFlush)
   writer 
= getWriter();
 }

 
public BaseLog() {
  
super();
 }

 
public int getRetryCount() {
  
return retryCount;
 }

 
public void setRetryCount(int retry) {
  retryCount 
= retry;
 }

 
public boolean isWritingTimeStamp() {
  
return writeTimeStamp;
 }

 
public void setTimeStamp(boolean b) {
  writeTimeStamp 
= b;
 }

 
public void setLogFileSize(long size) {
  logFileSize 
= size;
 }

 
public long getLogFileSize() {
  
return logFileSize;
 }

 
public static void putLog(HttpServletRequest request, String path,
   String fileSize, String backTime, String hotelid,
   String subscriberid, String pagetitle, String page_url,
   String[] adinfo) 
throws IOException {
  
// 取得URL。
  URI = getURL(request);
  
// 日志文件消息。
  String message = "," + hotelid + "," + subscriberid + "," + pagetitle
    
+ "," + URI;
  
// 取得当前日志文件的路径
  String logFilePath = path + "epgpagelog.log";
  
  
// 声明Log类
  BaseLog log = new BaseLog(logFilePath, true, fileSize, backTime);

  
// 获得当前日志文件。
  File logFile = new File(logFilePath);
  
  
if(logFile.exists()){
         
// 看文件是否需要备份,执行日志文件备份方法。
   log.backupLog(path, logFilePath, hotelid);
  }
else{
   logFile.createNewFile();
  }

  
  
// 打印日志消息。
  log.printLog(message);
  
 }

    
public static void putLog(HttpServletRequest request,String logpath,String user) throws IOException {
     URI 
= getURL(request);
        String message 
= user + " : URL:" + URI;
     Calendar   cal   
=   Calendar.getInstance();   
     SimpleDateFormat   formatter   
=   new   SimpleDateFormat("yyyyMMdd");   
     String   dCallTime
=formatter.format(cal.getTime());   
        JCCLog log 
= new JCCLog(logpath+dCallTime+".log"false);
        log.printLog(message);
    }

    
 
public static String getURL(HttpServletRequest request) {
  String path 
= request.getHeader("REFERER");
  
//String URI = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  return path;
 }

 
private void backupLog(String path, String logFilePath, String hotelid) {
  
// 判断文件控制的大小是多少,如果小于0,退出。
  if (logFileSize <= 0)
   
return;
  
// 自动刷新
  if (!autoFlush)
   
return;
  
// 定义备份的文件。
  File backup = null;
  
// 获得当前日志文件。
  File logFile = new File(logFilePath);
  
  FileReader fr;
  
  String line 
= "";
  
  String createTime 
= "";
  
  
long create = 0L;
  
  
// 取得系统时间。
  Calendar cal = Calendar.getInstance();
  SimpleDateFormat formatter 
= new SimpleDateFormat("yyyyMMddHHmm");
  String modifyTime 
= formatter.format(cal.getTime());
  
long nowTime = Long.parseLong(modifyTime);
  
  
try {
   fr 
= new FileReader(logFilePath);
   BufferedReader br 
= new BufferedReader(fr); 
   line 
= br.readLine();
   br.close();
   fr.close();
  }
 catch (FileNotFoundException e1) {
   e1.printStackTrace();
  }
catch (IOException e1) {
   e1.printStackTrace();
  }

 
  createTime 
= line.substring(016).replaceAll("-""").replaceAll(" """).replaceAll(":""").replaceAll("%20""");
  
  
  create 
= Long.parseLong(createTime);
  
// 当日志文件大小超过限制的大小时。
  if (logFile.length() > logFileSize || (nowTime - create) > fileBackTime) {
   
// 取得系统时间。
   SimpleDateFormat formatter2 = new SimpleDateFormat(
     
"yyyy_MM_dd_HH_mm_ss");
   String dCallTime 
= formatter2.format(cal.getTime());
   
// 定义备份文件的路径和文件名。
   String backupFile = path + "Epgpagelog_" + hotelid + "_"
     
+ dCallTime + ".log";
   backup 
= new File(backupFile);
   
   
// 将日志文件重命名。
   if (!logFile.renameTo(backup)) {
    System.err.println(
"不能重命名文件 " + logFile.getName() + " 到 "
      
+ backup.getName());
    System.err.println(
"可能已经备份了日志文件。 " + logFile.getName());
   }

   
   
try {
    
// 创建文件。
    logFile.createNewFile();
   }
 catch (IOException e) {
    
throw new RuntimeException("不能创建新文件 : " + logFile.getName());
   }

  }

 }

 
private PrintWriter getWriter() throws IOException {
  
return new PrintWriter(new BufferedWriter(new FileWriter(path, true)),
    
true);
 }

 
private String getMessage(String msg) {
  String message 
= "";
  String linesep 
= System.getProperty("line.separator");
  StringTokenizer st 
= new StringTokenizer(msg, linesep);
  
while (st.hasMoreTokens())
   message 
+= st.nextToken() + " ";
  
return message.trim();
 }

 
private void checkError(PrintWriter pr) throws IOException {
  
if (pr.checkError())
   
throw new IOException("IOException occurred while writing to "
     
+ path);
 }

 
public synchronized void printLog(String msg) {
  PrintWriter logWriter 
= null;
  FileNotFoundException fileNotFound 
= null;
  String message 
= getMessage(msg);
  
try {
   
for (int i = 0; i < retryCount; i++{
    
try {
     
if (autoFlush)
      logWriter 
= new PrintWriter(new BufferedWriter(
        
new FileWriter(path, true)), true);
     
break;
    }
 catch (FileNotFoundException e) {
     fileNotFound 
= e;
     Thread.sleep(RETRY_INTERVAL);
    }

   }

   
//end of retry. So time to throw a FileNotFoundException
   if (autoFlush && logWriter == null{
    
throw new RuntimeException(fileNotFound.toString());
   }

   
try {
    
if (writeTimeStamp) {
     String date 
= logTimeStamp.format(new Date(System
       .currentTimeMillis()));
     
if (autoFlush) {
      logWriter.print(date);
      checkError(logWriter);
     }
 else {
      writer.print(date);
      checkError(writer);
     }

    }

    
if (autoFlush) {
     logWriter.println(message);
     
//            logWriter.println();
     checkError(logWriter);
    }
 else {
     writer.println(message);
     
//            writer.println();
     checkError(writer);
    }

   }
 finally {
    
if (autoFlush)
     logWriter.close();
   }

  }
 catch (IOException e) {
   
throw new RuntimeException(e.toString());
  }
 catch (InterruptedException e) {
   
throw new RuntimeException(e.toString());
  }

 }

 
public synchronized void printLog(Throwable ex) {
  printLog(ex.toString());
 }

 
public synchronized void printStackTrace(Throwable ex) {
  PrintWriter logWriter 
= null;
  FileNotFoundException fileNotFound 
= null;
  
try {
   
for (int i = 0; i < retryCount; i++{
    
try {
     
if (autoFlush)
      logWriter 
= new PrintWriter(new BufferedWriter(
        
new FileWriter(path, true)), true);
     
break;
    }
 catch (FileNotFoundException e) {
     fileNotFound 
= e;
     Thread.sleep(RETRY_INTERVAL);
    }

   }

   
//end of retry. So time to throw a FileNotFoundException
   if (autoFlush && logWriter == null{
    
throw new RuntimeException(fileNotFound.toString());
   }

   
try {
    
if (writeTimeStamp) {
     String date 
= logTimeStamp.format(new Date(System
       .currentTimeMillis()));
     
if (autoFlush) {
      logWriter.print(date);
      checkError(logWriter);
     }
 else {
      writer.print(date);
      checkError(writer);
     }

    }

    
if (autoFlush) {
     ex.printStackTrace(logWriter);
     logWriter.println();
     checkError(logWriter);
    }
 else {
     ex.printStackTrace(writer);
     writer.println();
     checkError(writer);
    }

   }
 finally {
    
if (autoFlush)
     logWriter.close();
   }

  }
 catch (IOException e) {
   
throw new RuntimeException(e.toString());
  }
 catch (InterruptedException e) {
   
throw new RuntimeException(e.toString());
  }

 }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值