How to use Android Log API’s in Kotlin to print logs ?

Kotlin initializes the variables in different way than JAVA hence if you are too much used to write code using JAVA for android API’s, you may face some problems migrating to Kotlin.

Here, I am showing a simple way to initialize the global TAG string and use standard android logging API’s to print the logs in logcat using Kotlin language.

package com.example.myexample

import android.util.Log

class MainActivity : AppCompatActivity(){
    private val TAG = "MyLogTag"

    override fun onCreate(savedInstanceState: Bundle?) {
        var variable = 2
        super.onCreate(savedInstanceState)

        Log.d(TAG, "Simple Log String")
        Log.d(TAG, "Log String with Variable Values printed: "+ variable)
    }

}

Notice the major different between Kotlin and Java is,

In JAVA use use,

static final String TAG = "MyLogTag";

Whereas in Kotlin, this can be initialized as below and no semicolon required at end.

private val TAG = "MyLogTag"

In above Activity code, we have showed two examples to print the logs as,

Log.d(TAG, "Simple Log String")

This shows, how you can print the simple string in logcat.

Log.d(TAG, "Log String with Variable Values printed: "+ variable)

This shows if we want to print some values of variables in the logcat.

Leave a Comment