Android 将日志写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1756296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:36:00  来源:igfitidea点击:

Android Writing Logs to text File

android

提问by y ramesh rao

I'm Trying to Write Logs to Custom Log.txt File on Android File using this code of Mine but then this method creates file but contains nothing. Basically I want to read previous contents of the file and then append my data with the existing content.

我正在尝试使用我的此代码将日志写入 Android 文件上的自定义 Log.txt 文件,但此方法创建了文件但不包含任何内容。基本上我想阅读文件的先前内容,然后将我的数据附加到现有内容中。

The Code is as follows :

代码如下:

public static void write(String str) 
    {
        InputStream fileInputStream = null;
        FileOutputStream fileOutpurStream = null;
        try
        { 
            fileInputStream = new FileInputStream(file);
            fileOutpurStream = new FileOutputStream(file);
            if(file.exists())
            {
                int ch = 0;
                int current = 0;
                StringBuffer buffer = new StringBuffer();
                while((ch = fileInputStream.read()) != -1)
                {
                    buffer.append((char) ch);
                    current++;
                }
                byte data[]=new byte[(int)file.length()];
                fileInputStream.read(data);   
                fileOutpurStream.write(data);
                fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
                fileOutpurStream.flush();
            } 
            else
            {   
                file.createNewFile();
                fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
                fileOutpurStream.flush();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fileInputStream.close();
                fileOutpurStream.flush();
                fileOutpurStream.close();
                fileOutpurStream = null;
                fileInputStream = null;
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

回答by outkkast

Hope this can help...

希望这可以帮助...

public void appendLog(String text)
{       
   File logFile = new File("sdcard/log.file");
   if (!logFile.exists())
   {
      try
      {
         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.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

回答by Kiran

For those new to Java logging in general and Android logging

对于一般 Java 日志记录和 Android 日志记录的新手

  1. Log4jis generic java logging implementation and is now a project of Apache software foundation. It is not Android specific and so has some incompatibilities with Android.
  2. SL4J is not a logging implementation, It is an abstraction layer. It helps avoid a situations like, each 3rd party library dependencies to a project, trying to using its own logging implementation like Log4j. Source.
  1. Log4j是通用的 java 日志实现,现在是 Apache 软件基金会的一个项目。它不是 Android 特定的,因此与 Android 有一些不兼容。
  2. SL4J 不是日志记录实现,它是一个抽象层。它有助于避免诸如每个 3rd 方库依赖于项目的情况,尝试使用自己的日志记录实现,如 Log4j。来源

Some options for logging to txt in Android are below

在 Android 中登录到 txt 的一些选项如下

  1. Use logcat -fas in this answerto log to file. Note that from Android 4.2, READ_LOGS permission doesn't have any impact and every Application (unless phone is rooted) could only read its own logs. The disadvantage here is logcat buffer is circular and has a size limit. You might not get earlier logs.
  2. Use microlog4android( written for mobile devices like Android ) as in earlier answer. There could be a way, but I couldn't figure, how to use microlog4Android for logging to application internal storage. Only option for logs path was external storage like sdcard and so I couldn't use it.
  3. Use Log4jwith android-logging-log4j. What does android-logging-log4j do ? It makes Log4j easier to use in Android by giving two functions.

    • option to send logs to logcat in addition to logging file
    • a simple way to set Log4j configuration options like file path, max file size, number of backups etc by providing LogConfigurator class.

    Simple example below. Notice that loggerobject in below example is a Log4j object returned and not an android-logging-log4j class. So android-logging-log4j is used only for configuring Log4j.

  4. Yet to try LogBack. LogBack is developed by same person who came up with Log4J 1.x and SL4J libraries. Not related to Log4j 2.x though.
  1. logcat -f在此答案中使用as登录到文件。请注意,从 Android 4.2 开始,READ_LOGS 权限没有任何影响,每个应用程序(除非手机已 root)只能读取自己的日志。这里的缺点是 logcat 缓冲区是循环的并且有大小限制。您可能无法获得较早的日志。
  2. 使用microlog4android(为 Android 等移动设备编写),如前面的答案。可能有一种方法,但我想不通,如何使用 microlog4Android 登录到应用程序内部存储。日志路径的唯一选项是像 sdcard 这样的外部存储,所以我无法使用它。
  3. Log4jandroid-logging-log4j 一起使用。android-logging-log4j 有什么作用?它通过提供两个功能使 Log4j 在 Android 中更易于使用。

    • 除了日志文件之外,还可以选择将日志发送到 logcat
    • 通过提供 LogConfigurator 类来设置 Log4j 配置选项(如文件路径、最大文件大小、备份数量等)的简单方法。

    下面的简单例子。请注意,logger下面示例中的对象是返回的 Log4j 对象,而不是 android-logging-log4j 类。所以android-logging-log4j只用于配置Log4j。

  4. 尚未尝试LogBack。LogBack 是由提出 Log4J 1.x 和 SL4J 库的同一个人开发的。虽然与 Log4j 2.x 无关。

Steps for using Log4j in Android.

在 Android 中使用 Log4j 的步骤。

  1. Add both log4j-1.2.x.jarand android-logging-log4j-1.0.3.jarto the libs folder.

  2. Add permissions only if using external storage
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  3. Write Log4jhelper class

    package com.example.logger;
    
    import android.os.Environment;
    import de.mindpipe.android.logging.log4j.LogConfigurator;
    
    public class Log4jHelper {
        private final static LogConfigurator mLogConfigrator = new LogConfigurator();
    
        static {
            configureLog4j();
        }
    
        private static void configureLog4j() {
            String fileName = Environment.getExternalStorageDirectory() + "/" + "log4j.log";
            String filePattern = "%d - [%c] - %p : %m%n";
            int maxBackupSize = 10;
            long maxFileSize = 1024 * 1024;
    
            configure( fileName, filePattern, maxBackupSize, maxFileSize );
        }
    
        private static void configure( String fileName, String filePattern, int maxBackupSize, long maxFileSize ) {
            mLogConfigrator.setFileName( fileName );
            mLogConfigrator.setMaxFileSize( maxFileSize );
            mLogConfigrator.setFilePattern(filePattern);
            mLogConfigrator.setMaxBackupSize(maxBackupSize);
            mLogConfigrator.setUseLogCatAppender(true);
            mLogConfigrator.configure();
    
        }
    
        public static org.apache.log4j.Logger getLogger( String name ) {
            org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger( name );
            return logger;
        }
    }
    
  4. In Activity class

    org.apache.log4j.Logger log= Log4jHelper.getLogger( "YourActivity" );
    log.error("Error");
    log.info("Info");
    log.warn("Warn");
    
  1. log4j-1.2.x.jarandroid-logging-log4j-1.0.3.jar 添加到 libs 文件夹。

  2. 仅在使用外部存储时添加权限
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  3. 编写Log4j助手类

    package com.example.logger;
    
    import android.os.Environment;
    import de.mindpipe.android.logging.log4j.LogConfigurator;
    
    public class Log4jHelper {
        private final static LogConfigurator mLogConfigrator = new LogConfigurator();
    
        static {
            configureLog4j();
        }
    
        private static void configureLog4j() {
            String fileName = Environment.getExternalStorageDirectory() + "/" + "log4j.log";
            String filePattern = "%d - [%c] - %p : %m%n";
            int maxBackupSize = 10;
            long maxFileSize = 1024 * 1024;
    
            configure( fileName, filePattern, maxBackupSize, maxFileSize );
        }
    
        private static void configure( String fileName, String filePattern, int maxBackupSize, long maxFileSize ) {
            mLogConfigrator.setFileName( fileName );
            mLogConfigrator.setMaxFileSize( maxFileSize );
            mLogConfigrator.setFilePattern(filePattern);
            mLogConfigrator.setMaxBackupSize(maxBackupSize);
            mLogConfigrator.setUseLogCatAppender(true);
            mLogConfigrator.configure();
    
        }
    
        public static org.apache.log4j.Logger getLogger( String name ) {
            org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger( name );
            return logger;
        }
    }
    
  4. 在活动类

    org.apache.log4j.Logger log= Log4jHelper.getLogger( "YourActivity" );
    log.error("Error");
    log.info("Info");
    log.warn("Warn");
    

Example Source. Note that, log4j 2.x ( improved functionalities ) rewritten from scratch is not backward comptible with log4j 1.x. So you have to use log4j 1.2.x jar with android-logging-log4j jar. I was able to log to application internal file and later email the file with setReadable(true, false)

示例源。请注意,从头开始重写的 log4j 2.x(改进的功能)不能与 log4j 1.x 向后兼容。因此,您必须将 log4j 1.2.x jar 与 android-logging-log4j jar 一起使用。我能够登录到应用程序内部文件,然后通过电子邮件发送文件setReadable(true, false)

回答by Henry Bennett

microlog4android works for me but the documentation is pretty poor. All they need to add is a this is a quick start tutorial.

microlog4android 对我有用,但文档很差。他们需要添加的只是一个快速入门教程

Here is a quick tutorial I found.

这是我找到的快速教程。

  1. Add the following static variable in your main Activity:

    private static final Logger logger = LoggerFactory.getLogger();
    
  2. Add the following to your onCreate()method:

    PropertyConfigurator.getConfigurator(this).configure();
    
  3. Create a file named microlog.propertiesand store it in assetsdirectory

  4. Edit the microlog.propertiesfile as follows:

    microlog.level=DEBUG
    microlog.appender=LogCatAppender;FileAppender
    microlog.formatter=PatternFormatter
    microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
    
  5. Add logging statements like this:

    logger.debug("M4A");
    
  1. 在主活动中添加以下静态变量:

    private static final Logger logger = LoggerFactory.getLogger();
    
  2. 将以下内容添加到您的onCreate()方法中:

    PropertyConfigurator.getConfigurator(this).configure();
    
  3. 创建一个名为的文件microlog.properties并将其存储在assets目录中

  4. 编辑microlog.properties文件如下:

    microlog.level=DEBUG
    microlog.appender=LogCatAppender;FileAppender
    microlog.formatter=PatternFormatter
    microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
    
  5. 添加这样的日志语句:

    logger.debug("M4A");
    

For each class you create a logger object as specified in 1)

为每个类创建一个记录器对象,如 1)

6.You may be add the following permission:

6.您可以添加以下权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Here is the sourcefor tutorial

这是教程的来源

回答by BeMeCollective

Warning: I may be totally misunderstanding you, but if all you want is a log file, why sweat?

警告:我可能完全误解了你,但如果你想要的只是一个日志文件,为什么要出汗呢?

Put this in a bat file (change the path to your tools directory, and yourappname is of course your app's name):

把它放在一个 bat 文件中(改变你的工具目录的路径,你的appname当然是你的应用程序的名字):

cd "C:\devAndroid\Software\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools"
adb logcat -v time   ActivityManager:W  yourappname:D  *:W >"C:\devAndroid\log\yourappname.log"

Then in your code just do something similar to this:

然后在你的代码中做类似的事情:

Log.d("yourappname", "Your message");

To create the log, connect the USB cable and run your bat file.

要创建日志,请连接 USB 电缆并运行您的 bat 文件。

Regards

问候

回答by klimat

Use slf4androidlib.
It's simple implementation of slf4j apiusing android java.util.logging.*.

使用slf4android库。
这是使用 android java.util.logging.*的slf4j api的简单实现。

Features:

特征:

  • logging to file out of the box
  • logging to any other destination by LoggerConfiguration.configuration().addHandlerToLogger
  • shake your device to send logs with screenshot via email
  • really small, it tooks only ~55kB
  • 开箱即用地登录到文件
  • 登录到任何其他目的地 LoggerConfiguration.configuration().addHandlerToLogger
  • 摇动您的设备以通过电子邮件发送带有屏幕截图的日志
  • 真的很小,只需要~55kB

slf4android is maintained mainly by @miensol.

slf4android 主要由@miensol维护。

Read more about slf4android on our blog:

在我们的博客上阅读有关 slf4android 的更多信息:

回答by darius

You should take a look at microlog4android. They have a solution ready to log to a file.

你应该看看microlog4android。他们有一个解决方案可以记录到文件中。

http://code.google.com/p/microlog4android/

http://code.google.com/p/microlog4android/

回答by AndroidOptimist

This may be late but hope this may help.. Try this....

这可能会晚,但希望这可能会有所帮助..试试这个....

public void writefile()
    {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        File myFile = new File(externalStorageDir , "yourfilename.txt");

        if(myFile.exists())
        {
           try
           {

        FileOutputStream fostream = new FileOutputStream(myFile);
        OutputStreamWriter oswriter = new OutputStreamWriter(fostream); 
        BufferedWriter bwriter = new BufferedWriter(oswriter);   
        bwriter.write("Hi welcome ");
        bwriter.newLine();            
        bwriter.close(); 
        oswriter.close(); 
        fostream.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
        else
        {
            try {
                myFile.createNewFile();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }

here bfwritter.newlinewrites your text into the file. And add the permission

这里bfwritter.newline将您的文本写入文件。并添加权限

 <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>

in your manifest file without fail.

在您的清单文件中没有失败。

回答by Nova

I solved this problem with following piece of code in command line way:

我以命令行方式使用以下代码解决了这个问题:

File outputFile = new File("pathToFile"); 
Runtime.getRuntime().exec("logcat -c");
Runtime.getRuntime().exec("logcat -v time -f " + outputFile.getAbsolutePath())

Where "time" option adds metadata field details for date, invocation time, priority/tag, and PID of the process issuing the message.

其中“时间”选项为日期、调用时间、优先级/标签和发出消息的进程的 PID 添加元数据字段详细信息。

Then in your code just do something similar to this (using android.util.Log):

然后在你的代码中做一些类似的事情(使用 android.util.Log):

Log.d("yourappname", "Your message");

回答by Nate

In general, you must have a file handle before opening the stream. You have a fileOutputStream handle beforecreateNewFile() in the else block. The stream does not create the file if it doesn't exist.

通常,在打开流之前您必须有一个文件句柄。在 else 块中的 createNewFile()之前,您有一个 fileOutputStream 句柄。如果文件不存在,流不会创建文件。

Not really android specific, but that's a lot IO for this purpose. What if you do many "write" operations one after another? You will be reading the entire contents and writing the entire contents, taking time, and more importantly, battery life.

不是真正的android特定的,但是为此目的有很多IO。如果您一个接一个地执行许多“写入”操作怎么办?您将阅读全部内容并编写全部内容,这需要时间,更重要的是电池寿命。

I suggest using java.io.RandomAccessFile, seek()'ing to the end, then writeChars() to append. It will be much cleaner code and likely much faster.

我建议使用 java.io.RandomAccessFile,seek()'ing 到最后,然后 writeChars() 追加。这将是更干净的代码,并且可能会更快。

回答by Volker Voecking

I have created a simple, lightweight class (about 260 LoC) that extends the standard android.util.Log implementation with file based logging:
Every log message is logged via android.util.Log and also written to a text file on the device.

我创建了一个简单的轻量级类(大约 260 LoC),它使用基于文件的日志记录扩展了标准的 android.util.Log 实现:
每条日志消息都通过 android.util.Log 记录,并写入设备上的文本文件。

You can find it on github:
https://github.com/volkerv/FileLog

你可以在 github 上找到它:https:
//github.com/volkerv/FileLog