栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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(); 
  } 
   
  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; 
  } 
 
   
  public synchronized void log(String logMsg) { 
    this.writer.println(new java.util.Date() + ": " + logMsg); 
  } 
   
  public synchronized void log(Exception ex) { 
    writer.println(new java.util.Date() + ": "); 
    ex.printStackTrace(writer); 
  } 
 
   
  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); 
    } 
  } 
   
  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)); 
  } 
   
  @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"); 
  } 
   
} 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/146579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号