Android Studio Logging
To be a great developer, we need to cultivate a “debugging mindset” as well as build up defensive programming practices that make writing error-prone code less likely. When developing apps, we often find ourselves in the role of a coding investigator—hunting for clues and answers to why our app is crashing or not working as expected.
The Logcat window in Android Studio displays messages to developers—both errors in the code or information and messages we write ourselves using the
Log class. It displays messages in real-time and keeps a history so we can view older messages. Most Android developers depend heavily on logcat during development to debug their applications.
Write log messages
Log class allows us to create log messages that appear in Logcat. Generally, we should use the following log methods, listed in order from the highest to the lowest priority.
Log.e(String, String) // Error
Log.w(String, String) // Warning
Log.i(String, String) // Information
Log.d(String, String) // Debug
Log.v(String, String) // Verbose
Log method, the first parameter is a unique tag and the second parameter is the message. The tag of a system log message is a short string indicating the system component from which the message originates. Your tag can be any string that you find helpful, such as the name of the current class.
private static final String TAG = "MainActivity"; ... Log.i(TAG, "Greetings from Main Activity");
In the example above, our tag is the string
"MainActivity"—named after the class it is found in. The message is the string
"Greetings from Main Activity".
Set the log level
We can control the number of messages that appear by setting the log level. We can display all the messages, or just the messages indicating a level of severity of our choice.
Logcat will continue to capture all messages regardless of the log level settings we choose to see displayed.
In the Log level dropdown we may select the following values:
Verbose: Show all log messages (the default).
Debug: Show debug log messages that are useful during development only, as well as the message levels lower in this list.
Info: Show expected log messages for regular usage, as well as the message levels lower in this list.
Warn: Show possible issues that are not yet errors, as well as the message levels lower in this list.
Error: Show issues that have caused errors, as well as the message level lower in this list.
Assert: Show issues that the developer expects should never happen.
Log message format
The loge message format is:
date time PID-TID/package priority/tag: message
2020-01-13 16:57:57.124 21711-21711/com.example.helloworld I/MainActivity: Main Activity
PID-TID (Process Identifier - Thread Identifier): 21711-21711
message: Main Activity