Skip to content
DeveloperMemos

Printing to the Command Line in Android

Android, Command Line, Logging1 min read

When developing Android applications, it's often essential to have a way to print output to the command line for debugging or informational purposes. In this article, we will explore different techniques for printing to the command line in Android using Kotlin. We will cover three different approaches and provide examples to help you get started with logging in your Android projects.

1. Using Logcat

One of the most common ways to print output in Android is by using the Log class from the Android SDK. The Log class provides methods to write log messages at different levels, such as Log.d() for debug messages, Log.i() for informational messages, and Log.e() for error messages. Here's an example:

1import android.util.Log
2
3// ...
4
5Log.d("TAG", "This is a debug message")
6Log.i("TAG", "This is an informational message")
7Log.e("TAG", "This is an error message")

By default, log messages are displayed in the Logcat console within Android Studio. You can filter the logs based on tags or log levels to focus on the relevant information.

2. Using System.out

Another way to print output to the command line in Android is by using the System.out stream. This approach is similar to printing to the console in traditional Java applications. Here's an example:

1fun printToConsole() {
2 System.out.println("Printing to the console")
3}

However, it's important to note that when running an Android application, the output of System.out is not directly visible in the command line. Instead, you can observe the logs in the Logcat console by filtering the tag "System.out."

3. Using Timber

Timber is a lightweight logging library for Android that provides additional features and flexibility compared to the built-in Log class. It allows you to create custom logging tags, log different levels of messages, and even add additional information such as the calling class and line number. To use Timber, you will need to add it as a dependency in your project. Here's an example:

1import timber.log.Timber
2
3// ...
4
5class MainActivity : AppCompatActivity() {
6
7 override fun onCreate(savedInstanceState: Bundle?) {
8 super.onCreate(savedInstanceState)
9 setContentView(R.layout.activity_main)
10
11 Timber.plant(Timber.DebugTree())
12
13 Timber.d("This is a debug message")
14 Timber.i("This is an informational message")
15 Timber.e("This is an error message")
16 }
17}

Timber provides various useful features, including the ability to plant different trees (such as the DebugTree) for different build types or configurations. If you want to know more about Timber be sure to check out our other post about it!