Logging in android applications

Logging in Android Applications

Overview

This tutorial provides the required code snippets in order to add logging capabilities in Android applications.

Prerequisite: Make sure to read the overview of client-side log collection.

Enabling log capture

By default, log capture is enabled. Log capture saves logs to the client and can be enabled or disabled programmatically. Logs are sent to the server with an explicit send call, or with auto log

Note: Enabling log capture at verbose levels can impact the consumption of the device CPU, file system space, and the size of the payload when the client sends logs over the network.

To disable log capturing:

Sending captured logs

Send logs to the MobileFirst according to your application’s logic. Auto log send can also be enabled to automatically send logs. If logs are not sent before the maximum size is reached, the log file is then purged in favor of newer logs.

Note: Adopt the following pattern when you collect log data. Sending data on an interval ensures that you are seeing your log data in near real-time in the MobileFirst Analytics Console.

To ensure that all captured logs are sent, consider one of the following strategies:

  • Call the send method at a time interval.
  • Call the send method from within the app lifecycle event callbacks.
  • Increase the max file size of the persistent log buffer (in bytes):

Auto log sending

By default, auto log send is enabled. Each time a successful resource request is sent to the server, the captured logs are also sent, with a 60-second minimum interval between sends. Auto log send can be enabled or disabled from the client.

Change autoSendLog interval

By default autoSendLog interval is set as 60 seconds. AutoSendLog interval can be altered using following method.

To set autoSendLog interval as 120 seconds, see the following.

Fine-tuning with the Logger API

The MobileFirst client SDK makes internal use of the Logger API. By default, you are capturing log entries made by the SDK. To fine-tune log collection, use logger instances with package names. You can also control which logging level is captured by the analytics using server-side filters.

As an example to capture logs only where the level is ERROR for the myApp package name, follow these steps.

Use a logger instance with the myApp package name.

Optional: Specify a filter to restrict log capture and log output to only the specified level and package programmatically.

Optional: Control the filters remotely by fetching a server configuration profile.

Fetching server configuration profiles

Logging levels can be set by the client or by retrieving configuration profiles from the server. From the MobileFirst Analytics Console, a log level can be set globally (all logger instances) or for a specific package or packages.

For information on configuring the filter from the MobileFirst Analytics Console, see Configuring log filters.

For the client to fetch the configuration overrides that are set on the server, the updateConfigFromServer method must be called from a place in the code that is regularly run, such as in the app lifecycle callbacks.

Читайте также:  Самая простая звонилка для андроид

Logging example

Outputs to a browser JavaScript console, LogCat, or Xcode console.

Источник

Android Essentials: Application Logging

In this quick tip tutorial, you’ll learn how to use application logging support in your Android applications for diagnostic purposes.

This quick tip shows you the steps to incorporate logging support into your applications and then use the LogCat logging utility to monitor your application’s log output, either on the emulator or a device that is attached to Eclipse via the debugger. This skill is invaluable for debugging issues, even when great debuggers are available for stepping through code.

Step 1: Create an Android Application

Begin by creating an Android project. Implement your Android application as normal. Once you’ve setup your Android project, you are ready to proceed with this quick tip.

Step 2: Logging Options for Android Applications

The Android SDK includes a useful logging utility class called android.util.Log. Logging messages are categorized by severity (and verbosity), with errors being the most severe, then warnings, informational messages, debug messages and verbose messages being the least severe. Each type of logging message has its own method. Simply call the method and a log message is created. The message types, and their related method calls are:

  • The Log.e() method is used to log errors.
  • The Log.w() method is used to log warnings.
  • The Log.i() method is used to log informational messages.
  • The Log.d() method is used to log debug messages.
  • The Log.v() method is used to log verbose messages.
  • The Log.wtf() method is used to log terrible failures that should never happen. («WTF» stands for «What a Terrible Failure!» of course.)

The first parameter of each Log method is a string called a tag. It’s common practice to define a global static string to represent the overall application or the specific activity within the application such that log filters can be created to limit the log output to specific data. For example, you could define a string called TAG, as follows:

You will often find that the tag is defined as the class in which the Log statement occurs. This is a reasonable convention, but anything identifiable or useful to you will do.

Now anytime you use a Log method, you supply this tag. An informational logging message might look like this:

You can also pass a Throwable object, usually on Exception, that will allow the Log to print a stack trace or other useful information.

NOTE: Calling the Log.wtf() method will always print a stack trace and may cause the process to end with an error message. It is really intended only for extreme errors. For standard logging of exceptions, we recommend using the Log.e() method. The Log.wtf() method is available only in Android 2.2 or later. The rest are available in all versions of Android.

Step 3: Adding Log Support to an Activity Class

Now let’s add some logging to your Activity class. First, add the appropriate import statement for the logging class android.util.Log. Next, declare a logging tag for use within your class (or whole application); in this case, we call this variable DEBUG_TAG. Finally, add logging method calls wherever you want logging output. For example, you might add an informational log message within the onCreate() method of your Activity class.

Below is some sample code that illustrates how all these steps come together:

Step 4: Monitoring Application Log Output – The Easy Way

You can use the LogCat utility from within Eclipse to view the log output from an emulator or device. LogCat is integrated into Eclipse using the Android Development plug-in. You’ll find the LogCat panel integrated into the DDMS and Debug perspectives of Eclipse.

Читайте также:  Удобная галерея для андроида

Step 5:Monitoring Application Log Output – Creating Log Filters

As you can see, the basic LogCat logging output includes log data from lots of different sources. For debugging purposes, it can be useful to filter the output to only the tags for your specific application. This way, you can focus on your application log output, amidst all the clutter.

You can use the LogCat utility from within Eclipse to filter your log messages to the tag string you supplied for your application. To add a new filter, click the green plus sign button in the LogCat pane of Eclipse. Name the filter—perhaps using the tag name—and fill in the tag you want to filter on. A new tab is created in LogCat that will show only log messages that contain this tag. You can create filters that display items by severity level.

Performance Considerations with Logging

Logging output puts a damper on application performance. Excessive use can result in decreased application performance. At minimum, debug and verbose logging should be used only for development purposes and removed before release. It’s also a good idea to review other logging output before publication as well.

Conclusion

Logging is a very handy debugging and diagnostic technique used by developers. Use the logging class provided as part of the Android SDK to log important information about your application to LogCat, but make sure you review your application’s logging implementation prior to publication, as logging has performance drawbacks.

Источник

Android LogCat And Logging Best Practice

android.util.Log is the log class that provides the log function. It provides the below methods to log data into the LogCat console.

1. Android Log Methods.

  1. Log.v(): Print verbose level log data. The verbose level is the lowest log level, if you print so much this kind of log data, it is not meaningful.
  2. Log.d(): Print debug level log data. Debug level is one step higher than verbose level. Debug log data is usually useful in android application development and testing.
  3. Log.i(): Print info level log data. Info level is one step higher than debug level. Info log data is used to collect user actions and behaviors.
  4. Log.w(): Print warn level log data. Warn level is one step higher than info level. When you see this kind of log data, it means your code exists potential risks, you need to check your code carefully.
  5. Log.e(): Print error level log data. Error level is the highest level. It is always used in java code catch block to log exception or error information. This kind of log data can help you to find out the root cause of app crashes.

2. Android Log Methods Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ciBUMesUfVo

  1. This example is very simple. When you click the button, it will print above 5 kinds of log data in the LogCat console.
  2. When you input the search keyword LogActivity in the LogCat panel, the app log data will be filtered out. For each line of log data, there are the log time, class name, and log message.
  3. You can also filter out the log data by it’s type, verbose, info, debug, warn, or error. This can make log data search more easily and accurately, you can see the below demo video.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/zyUvmTF_Mzw

  1. Click the Settings icon in the LogCat panel, you can configure which column to be displayed for each line of the log.
  2. The columns include Show date and time, Show process and thread IDs(PID-TID), Show package name, Show tag, you can see it in the below picture.
Читайте также:  Гугл кип для андроида

Источник

Better Logging In Android Using Timber

While developing android applications we as developers tend to put in a lot of logs with in different different priorities for this sake android sdk comes in with a utility class Log, which does have utility methods to log our messages with different priorities the most common methods that we use for different cases like we uses Log.e(TAG,”message”) in the cases we want to show some error (this usually appears in red color in the logcat window of android studio), or Log.d(TAG, «message») when we want to print some message for the purpose of debugging, like value of some data.

Usually when the application development is completed and its the time to release the app on the play store, we need to remove all Log statement from the app, so that none of the application data such as user information, hidden application data, auth-tokens are available to user in logcat as plain text and this becomes a cumbersome task

There are several ways to tackle this problem

1. Condition based logging

In this we can make a public static boolean variable in Application class like in the below code snippet.

and use this variables value as check for logging like the code snippet below

and use this boolean variable at every place where you want to put a log message, and once you are ready to release the app, just set isDebug = false in the application class, but this approach puts in an extra line of code, which is completely unnecessary and can be avoided.

This simply can be achieved using android’s in built build configuration, BuildConfig. DEBUG can be used instead of that boolean variable for checking if the build type is release or debug.

2. ProGuard

This approach is all also a solution to this problem, you can render the Log class ineffective and can remove those statement in the release build by putting in

into the proguard rules file.

Here comes Timber, the best solution to tackle this problem

What if I tell you there exists a simple library called “Timber” which can log your messages and gives you the control over the flow of logs. Timber is a yet another cool library developed by an awesome developer Jake Wharton.

Adding timber to you project

To add timber to your android studio project, just paste in the below line in to /app/build.gradle file and sync the project.

Once the project is synced just plant a timber debug tree in the Application class, because as per the instruction on Timber’s github page and I quote it

Installation of Tree should be done as early as possible. The onCreate of your application is the most logical choice.

Here, Timber.DebugTree() prints the logs when your application type is debug application.

And that’s all we need to do in order to use timber. Wherever you have used that Log…(…) statement just remove that tag parameter and replace Log with Timber.

as you can see in the above gist, that it is not required to pass in the tag parameter in the Timber.d(. ) or Timber.e(. ) statement, as Timber automatically detects the class in which logs were written.

But there might me requirement when you need to specify a custom tag which can be simply achieved by

as shown in the above gist. More about Timber can be found at :

Источник

Оцените статью