【问题标题】:How to store Logs in a txt file using the android.util.log如何使用 android.util.log 将日志存储在 txt 文件中
【发布时间】:2012-09-19 08:37:04
【问题描述】:

我知道这个话题已经谈了很多,但不是这个意思。 我需要将日志存储在 .txt 文件中,但我不能使用 log4j 或除 android.util.log 之外的任何其他类 我有这个解决方案,但它不是最好的。 对于具有与以下相同的信息:Log.i(TAG, "An INFO Message"); 我得写……

ERROR = logLevel < 3;
WARNING = logLevel < 2;
INFO = logLevel < 1;
if (INFO){ 

    appendLog("LEVEL: I    TIME: "+java.util.GregorianCalendar.DAY_OF_MONTH +
                        "-"+ java.util.GregorianCalendar.MONTH +" "+GregorianCalendar.HOUR_OF_DAY +":"+GregorianCalendar.MINUTE +
                        ":"+GregorianCalendar.SECOND +"."+GregorianCalendar.MILLISECOND + "    PID: "+
                        android.os.Process.myPid()+ "    TID: "+android.os.Process.myTid()+ "    Application: com.example.myapplication"+
                        "    TAG:" +TAG+ "    TEXT: An INFO Message");
}

然后……

public void appendLog(String text) {        
    File logFile = new File("sdcard/log.txt"); 
    if (!logFile.exists()) { 
        try { 
            logFile.createNewFile(); 
        }catch (IOException e){ 
            e.printStackTrace(); 
      } 
   } 
   try { 
       BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));  
       buf.append(text); 
       buf.newLine(); 
       buf.close(); 
   } catch (IOException e) { 
       e.printStackTrace(); 
   } 
}

还有比这更优雅的解决方案吗?谢谢你帮助我。

【问题讨论】:

标签: android file logging


【解决方案1】:

这里附上简单的 Logger 类定义,你可以直接使用。 要将日志信息存储到 SDCARD 中的 Log.txt 文件中,请使用它。

package com.clientname.projectname;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;

import android.os.Environment;
import android.util.Log;

/**
 * @author Rakesh.Jha
 * Date - 07/10/2013
 * Definition - Logger file use to keep Log info to external SD with the simple method
*/

public class Logger {

    public static  FileHandler logger = null;
    private static String filename = "ProjectName_Log";

    static boolean isExternalStorageAvailable = false;
    static boolean isExternalStorageWriteable = false; 
    static String state = Environment.getExternalStorageState();

    public static void addRecordToLog(String message) {

        if (Environment.MEDIA_MOUNTED.equals(state)) { 
            // We can read and write the media 
            isExternalStorageAvailable = isExternalStorageWriteable = true; 
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
            // We can only read the media 
            isExternalStorageAvailable = true; 
            isExternalStorageWriteable = false; 
        } else { 
            // Something else is wrong. It may be one of many other states, but all we need 
            //  to know is we can neither read nor write 
            isExternalStorageAvailable = isExternalStorageWriteable = false; 
        }

        File dir = new File("/sdcard/Files/Project_Name");      
        if (Environment.MEDIA_MOUNTED.equals(state)) {  
            if(!dir.exists()) {
                Log.d("Dir created ", "Dir created ");
                dir.mkdirs();
            }

            File logFile = new File("/sdcard/Files/Project_Name/"+filename+".txt");

            if (!logFile.exists())  {
                try  {
                    Log.d("File created ", "File created ");
                    logFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try { 
                //BufferedWriter for performance, true to set append to file flag
                BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 

                buf.write(message + "\r\n");
                //buf.append(message);
                buf.newLine();
                buf.flush();
                buf.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

现在,一旦你创建了这个文件,你想将日志信息存储到 log.txt 文件中的任何地方,使用下面的代码。 -

package com.clientname.projectname;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;

/**

 * @author Rakesh.Jha
 * Date - 03/10/2013
 * Definition -  //ToDO

*/

public class MainActivity extends Activity {

    private static final String TAG = null;
    Logger logger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Testing     :","log"); // no need to do this line, use below line
        logger.addRecordToLog("Testing     : log " );

        logger.addRecordToLog("TAG MediaPlayer audio session ID: " );

        MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);//test is audio file, u have to keep in raw folder

        logger.addRecordToLog( "MediaPlayer audio session ID: " + mediaPlayer.getAudioSessionId()); 
        logger.addRecordToLog( "Media Player started " + "Started !");

        mediaPlayer.start(); // no need to call prepare(); create() does that for you
    }

    private void prepareMediaServer() { }
}

【讨论】:

    【解决方案2】:

    创建一个封装 Android 的 Log 类的封装类。这个包装类将通过另外将文本记录到文件中来扩展Log 类的功能。

    例子:

    public class MyLog{
        public static void i(String TAG, String message){
    
            // Printing the message to LogCat console
            Log.i(TAG, message);
    
            // Write the log message to the file
            appendLog(message);
        }
    
        public static void d(String TAG, String message){
            Log.d(TAG, message);
            appendLog(message);
        }
    
        // rest of log methods...
    }
    

    那么你应该这样使用它:

    MyLog.i("LEVEL 1", "Your log message here...");
    

    【讨论】:

    • 但它没有给我时间、TID、PID、应用程序名称……只给我消息。我正在寻求一种解决方案,我不必自己编写所有这些参数。当然,如果我将它包装在一个类中,我只需要编写一次,但看起来仍然不是最好的解决方案......还有其他解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    相关资源
    最近更新 更多