当前位置: 移动技术网 > IT编程>开发语言>Java > java异步写日志到文件中实现代码

java异步写日志到文件中实现代码

2019年07月22日  | 移动技术网IT编程  | 我要评论
java异步写日志到文件中详解 实现代码: package com.tydic.esutil; import java.io.file; impo

java异步写日志到文件中详解

实现代码:

package com.tydic.esutil; 
 
import java.io.file; 
import java.io.filewriter; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.printwriter; 
import java.util.properties; 
 
public class logwriter { 
// 日志的配置文件 
  public static final string log_configfile_name = "log.properties"; 
  // 日志文件名在配置文件中的标签 
  public static final string logfile_tag_name = "logfile"; 
   
  // 默认的日志文件的路径和文件名称 
  private final string default_log_file_name = "./logtext.log"; 
  // 该类的唯一的实例 
  private static logwriter logwriter; 
  // 文件输出流 
  private printwriter writer;  
  // 日志文件名 
  private string logfilename;  
  /** 
   * 默认构造函数 
   */ 
  private logwriter() throws logexception{ 
    this.init(); 
  } 
  private logwriter(string filename) throws logexception{ 
    this.logfilename = filename; 
    this.init(); 
  } 
  /** 
   * 获取logwriter的唯一实例。 
   * @return 
   * @throws logexception 
   */ 
  public synchronized static logwriter getlogwriter()throws logexception{ 
    if (logwriter == null){ 
      logwriter = new logwriter(); 
    } 
    return logwriter; 
  } 
  public synchronized static logwriter getlogwriter(string logfilename)throws logexception{ 
    if (logwriter == null){ 
      logwriter = new logwriter(logfilename); 
    } 
    return logwriter; 
  } 
 
  /** 
   * 往日志文件中写一条日志信息 
   * 为了防止多线程同时操作(写)日志文件,造成文件”死锁”。使用synchronized关键字 
   * @param logmsg  日志消息 
   */ 
  public synchronized void log(string logmsg) { 
    this.writer.println(new java.util.date() + ": " + logmsg); 
  } 
  /** 
   * 往日志文件中写一条异常信息 
   * 使用synchronized关键字。 
   * @param ex  待写入的异常 
   */ 
  public synchronized void log(exception ex) { 
    writer.println(new java.util.date() + ": "); 
    ex.printstacktrace(writer); 
  } 
 
  /** 
   * 初始化logwriter 
   * @throws logexception 
   */ 
  private void init() throws logexception{ 
    //如果用户没有在参数中指定日志文件名,则从配置文件中获取。 
    if (this.logfilename == null){ 
      this.logfilename = this.getlogfilenamefromconfigfile(); 
      //如果配置文件不存在或者也没有指定日志文件名,则用默认的日志文件名。 
      if (this.logfilename == null){ 
        this.logfilename = default_log_file_name; 
      } 
    } 
    file logfile = new file(this.logfilename); 
    try { 
      // 其中的filewriter()中的第二个参数的含义是:是否在文件中追加内容 
      // printwriter()中的第二个参数的含义是:自动将数据flush到文件中 
      writer = new printwriter(new filewriter(logfile, true), true); 
      system.out.println("日志文件的位置:" + logfile.getabsolutepath()); 
    } catch (ioexception ex) { 
      string errmsg = "无法打开日志文件:" + logfile.getabsolutepath(); 
      // system.out.println(errmsg); 
      throw new logexception(errmsg, ex); 
    } 
  } 
  /** 
   * 从配置文件中取日志文件名 
   * @return 
   */ 
  private string getlogfilenamefromconfigfile() {  
    try {  
      properties pro = new properties();  
      //在类的当前位置,查找属性配置文件log.properties  
      inputstream fin = getclass().getresourceasstream(log_configfile_name);  
      if (fin != null){ 
        pro.load(fin);//载入配置文件 
        fin.close();  
        return pro.getproperty(logfile_tag_name); 
      } else { 
        system.err.println("无法打开属性配置文件: log.properties" );  
      } 
    }catch (ioexception ex) {  
      system.err.println("无法打开属性配置文件: log.properties" );  
    } 
    return null; 
  } 
  //关闭logwriter 
  public void close() { 
    logwriter = null; 
    if (writer != null){ 
      writer.close(); 
    } 
  } 
 
  public static void main(string[] args) { 
    logwriter logger = null; 
    try { 
      string filename = "d:/temp/logger.log"; 
      logger = logwriter.getlogwriter(filename); 
//     logger.log("first log!"); 
//     logger.log("第二个日志信息"); 
//     logger.log("third log"); 
//     logger.log("第四个日志信息"); 
      string content="tableaa|device_number|13701010"; 
      stringbuffer sb=new stringbuffer(); 
      for(int i=0;i<1000000;i++){ 
        sb.append(content).append(i).append(";\n"); 
      } 
      content=sb.tostring(); 
      long starttime=system.currenttimemillis(); 
      logger.log(content); 
      long endtime=system.currenttimemillis(); 
      system.out.println("总消耗时间:"+(endtime-starttime)); 
      logger.close(); 
//     readfromfile.readfilebylines(filename); 
    } catch (logexception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

 

package com.tydic.esutil; 
 
public class aychwriter extends thread { 
  private string content; 
  public aychwriter(string content){ 
    this.content=content; 
  } 
  @override 
  public void run(){ 
    system.out.println("开始执行run()"); 
    logwriter logger = null; 
    string filename = "d:/temp/logger.log"; 
    long starttime=system.currenttimemillis(); 
    try { 
      logger = logwriter.getlogwriter(filename); 
      logger.log(this.content); 
    } catch (logexception e1) { 
      // todo auto-generated catch block 
      e1.printstacktrace(); 
    } 
 
    long endtime=system.currenttimemillis(); 
    system.out.println("总消耗时间:"+(endtime-starttime)); 
  } 
} 

测试类:

package com.tydic.esutil; 
 
import java.io.filewriter; 
import java.io.ioexception; 
 
import org.junit.test; 
 
public class test_test { 
  /** 
   * 同步向指定文件尾部写入字符串 
   */ 
public void testappendmethodb(string filename,string content) throws ioexception{ 
    try { 
      //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 
      filewriter writer = new filewriter(filename, true); 
      writer.write(content); 
      writer.close(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
    } 
 
/** 
 *调用上面同步写方法 
 */ 
  @test 
  public void testwritetofile() throws ioexception{ 
    string filename = "d:\\test.txt"; 
    string content="tableaa|device_number|13701010"; 
    stringbuffer sb=new stringbuffer(); 
    for(int i=0;i<100000;i++){ 
      sb.append(content).append(i).append(";\n"); 
    } 
    content=sb.tostring(); 
    long starttime=system.currenttimemillis(); 
    testappendmethodb(filename,content); 
    long endtime=system.currenttimemillis(); 
    system.out.println("总消耗时间:"+(endtime-starttime)); 
  } 
  /** 
   * 异步调用写方法 
   * @throws ioexception 
   * @throws interruptedexception 
   */ 
  @test 
  public void testasyncwritetofile() throws ioexception, interruptedexception{ 
    string filename = "d:\\test.txt"; 
    string content="tableaa|device_number|13701010"; 
    stringbuffer sb=new stringbuffer(); 
    for(int i=0;i<100000;i++){ 
      sb.append(content).append(i).append(";\n"); 
    } 
    content=sb.tostring(); 
    system.out.println("start write..."); 
    new aychwriter(content).start(); 
    system.out.println("write over..."); 
    thread.sleep(30000); //重要,如果主线程挂了,调用线程也停止了 
    system.out.println("main thread over"); 
  } 
   
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网