在Android应用程序中创建日志

对于Android应用程序,日志记录由android.util.Log类处理,这是一个基本的日志记录类,将日志存储在整个设备的循环缓冲区中。 可以在Eclipse的LogCat选项卡中查看设备的所有日志,或使用logcat命令读取该日志。 这是Eclipse中LogCat选项卡的标准日志输出:



图片

您可以在应用程序中使用五级日志,从最详细到最不详细:

  • 详细:有关仅在调试应用程序中编译但从不包含在发布应用程序中的消息,请参阅。
  • 调试:用于调试日志消息,这些消息总是经过编译,但是在运行时在发布应用程序中剥离。
  • 信息:有关将在调试和发行中编写的日志中的信息。
  • 警告:对于将在调试和发布中写入的日志中的警告。
  • 错误:对于将在调试和发布中写入的日志中的错误。

日志消息包括标识一组消息和该消息的标签。 默认情况下,所有标记的日志级别为Info ,这意味着,除非使用setprop命令更改日志级别,否则绝不显示DebugVerbose级别的消息。 因此,要将详细消息写入日志,应调用isLoggable方法以检查消息是否可以记录,然后调用logging方法:

if (!Log.isLoggable(logMessageTag, Log.Verbose))
   Log.v("MyApplicationTag", logMessage);

要显示特定标签的“调试和详细日志”消息,请在插入设备时运行setprop命令。如果重新引导设备,则必须再次运行该命令。

adb shell setprop log.tag.MyApplicationTag VERBOSE

不幸的是,从Android 4.0开始,应用程序只能读取自己的日志。 能够从另一个应用程序中读取日志对于调试很有用,但是在某些情况下,敏感信息会写入这些日志中,并且会创建恶意应用程序来检索它们。 因此,如果您需要发送日志文件进行调试,则需要使用android.util.Log类中的方法创建自己的日志类。 请记住,当应用程序未在调试模式下运行时,仅应显示InfoWarningError日志。 这是一个简单的记录器的示例,该记录器包装了对isLoggable的调用,并将日志消息存储在设备的主存储中(需要权限WRITE_EXTERNAL_STORAGE)和标准缓冲区:

/**
  * A logger that uses the standard Android Log class to log exceptions, and also logs them to a 
  * file on the device. Requires permission WRITE_EXTERNAL_STORAGE in AndroidManifest.xml.
  * @author Cindy Potvin
  */
 public class Logger
 {
 /**
   * Sends an error message to LogCat and to a log file.
   * @param context The context of the application.
   * @param logMessageTag A tag identifying a group of log messages. Should be a constant in the 
   *                      class calling the logger.
   * @param logMessage The message to add to the log.
   */
 public static void e(Context context, String logMessageTag, String logMessage) 
    {
    if (!Log.isLoggable(logMessageTag, Log.ERROR))
       return;

    int logResult = Log.e(logMessageTag, logMessage);
    if (logResult > 0) 
       logToFile(context, logMessageTag, logMessage);
    }

/**
   * Sends an error message and the exception to LogCat and to a log file.
   * @param context The context of the application.
   * @param logMessageTag A tag identifying a group of log messages. Should be a constant in the 
   *                      class calling the logger.
   * @param logMessage The message to add to the log.
   * @param throwableException An exception to log
   */
 public static void e(Context context, String logMessageTag, String logMessage, Throwable throwableException) 
    {
    if (!Log.isLoggable(logMessageTag, Log.ERROR))
       return;

    int logResult = Log.e(logMessageTag, logMessage, throwableException);
    if (logResult > 0) 
       logToFile(context, logMessageTag, logMessage + "\r\n" + Log.getStackTraceString(throwableException));
    }

// The i and w method for info and warning logs should be implemented in the same way as the e method for error logs.

/**
   * Sends a message to LogCat and to a log file.
   * @param context The context of the application.
   * @param logMessageTag A tag identifying a group of log messages. Should be a constant in the 
   *                      class calling the logger.
   * @param logMessage The message to add to the log.
   */
 public static void v(Context context, String logMessageTag, String logMessage) 
    {
                              // If the build is not debug, do not try to log, the logcat be 
                              // stripped at compilation.
    if (!BuildConfig.DEBUG || !Log.isLoggable(logMessageTag, Log.VERBOSE))
        return;

    int logResult = Log.v(logMessageTag, logMessage);
    if (logResult > 0) 
       logToFile(context, logMessageTag, logMessage);
    }

/**
   * Sends a message and the exception to LogCat and to a log file.
   * @param logMessageTag A tag identifying a group of log messages. Should be a constant in the 
   *                      class calling the logger.
   * @param logMessage The message to add to the log.
   * @param throwableException An exception to log
   */
 public static void v(Context context,String logMessageTag, String logMessage, Throwable throwableException) 
    {
                              // If the build is not debug, do not try to log, the logcat be 
                              // stripped at compilation.
    if (!BuildConfig.DEBUG || !Log.isLoggable(logMessageTag, Log.VERBOSE))
        return;

    int logResult = Log.v(logMessageTag, logMessage, throwableException);
    if (logResult > 0) 
       logToFile(context, logMessageTag,  logMessage + "\r\n" + Log.getStackTraceString(throwableException));
    }

// The d method for debug logs should be implemented in the same way as the v method for verbose logs.

/**
  * Gets a stamp containing the current date and time to write to the log.
  * @return The stamp for the current date and time.
  */
 private static String getDateTimeStamp()
    {
    Date dateNow = Calendar.getInstance().getTime();
                              // My locale, so all the log files have the same date and time format
    return (DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.CANADA_FRENCH).format(dateNow));
    }

/**
  * Writes a message to the log file on the device.
  * @param logMessageTag A tag identifying a group of log messages.
  * @param logMessage The message to add to the log.
  */
 private static void logToFile(Context context, String logMessageTag, String logMessage)
    {
    try
       {
                              // Gets the log file from the root of the primary storage. If it does 
                              // not exist, the file is created.
       File logFile = new File(Environment.getExternalStorageDirectory(), "TestApplicationLog.txt");
       if (!logFile.exists())
          logFile.createNewFile();
                              // Write the message to the log with a timestamp
       BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
       writer.write(String.format("%1s [%2s]:%3s\r\n", getDateTimeStamp(), logMessageTag, logMessage));
       writer.close();
                              // Refresh the data so it can seen when the device is plugged in a 
                              // computer. You may have to unplug and replug to see the latest 
                              // changes
      MediaScannerConnection.scanFile(context, 
                                      new String[] { logFile.toString() }, 
                                      null, 
                                      null);

       }
    catch (IOException e)
       {
       Log.e("com.cindypotvin.Logger", "Unable to log exception to file.");
       }
    }
 }

如果使用此类记录器将应用程序发布到应用程序商店或客户端,则应默认禁用日志记录,并在首选项中添加一个开关以启用按需记录。 如果始终启用记录器,则您的应用程序通常会写入主存储和logcat,这在一切正常工作时是不必要的开销。 另外,应以某种方式限制日志文件的大小,以避免填满主存储。

翻译自: https://www.javacodegeeks.com/2014/06/creating-logs-in-android-applications.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值