2012-11-26 37 views
1

我想实现自己的记录器,将日志写入文件。它可以从多个线程运行,并且问题是如何同步对日志文件的访问。同步访问文件

private synchronized static void writeToFile(String tag, String msg, 
     Throwable tr, Context ctx) { 
    try { 
     String s = System.getProperty("line.separator"); 
     File f = Environment.getExternalStorageDirectory(); 
     Log.i(TAG, "Path to app " + f.getAbsolutePath()); 
     File l = new File(f, "log.txt"); 
     if (!l.exists()) { 
      l.createNewFile(); 
     } 

     String e = Log.getStackTraceString(tr); 
     StringBuilder b = new StringBuilder(); 
     b.append(HttpCommand.getDateForUrl(System.currentTimeMillis())); 
     b.append(tag); 
     b.append(msg); 
     b.append(e); 
     b.append(s); 

     OutputStream out = new FileOutputStream(l); 
     out.write(b.toString().getBytes()); 
     out.flush(); 
     out.close(); 
    } catch (IOException e) { 
     Log.e(TAG, "Failed to create backup"); 
    } 
} 

是否足够同步通过类同步访问数据库,如果我通过它在不同的线程?

synchronized(X.class) { 
    writeTiFile() 
} 

回答

0

可以使用的ConcurrentLinkedQueue,把所有的消息队列,创建线程,从队列中取并将它写入文件。