Using automatic naming

Currently, we have a group of coroutines that are both short-lived and created inside a loop, so we are not interested in giving them specific names. In cases like this, we can have Kotlin assign an automatic identifier to each of them.

To do so, we simply need to change the configuration that we use to execute our application. By passing the -Dkotlinx.coroutines.debug VM flag, Kotlin will append a unique identifier to every coroutine that is created when we request the name of the current thread. In order to add this flag, you need to click the dropdown in the selector of Run/Debug Configuration, shown as follows, and select Edit Configurations:

Once this is done, you can add the flag in the VM Options section:

I recommend you keep this flag on during development and during test execution, including any automatic test execution that you may have as part of your pipeline—for example, if you use a continuous integration workflow, make sure that the tests are run with the flag enabled. This will allow you to have meaningful logs for errors that may be difficult to replicate.

As mentioned, adding this flag will affect the value of Thread.currentThread().name; when obtained inside a coroutine it will now include a unique ID for it. Because our current code is already depending on that property, we don't need to change any code. Executing it now will print a log that will be easier to analyze:

Now you can grep the log to find all the entries related to a specific coroutine, as long as you keep printing the name of the current thread.

You can create or use a logger that always prints the name of the thread. That way, you will automatically have the identifier of the coroutine in your logs; just make sure to configure the flag.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.85