IDE logging system
Logging in the IDE is based on the com.intellij.openapi.diagnostic.Logger class. This is an abstraction layer that allows different logging libraries (or their configurations) to be chosen by the IDE, without affecting most of the code. In the current setup, Log4J is used by the IDE at runtime. For details, see IdeaLogger , LoggerFactory and StartupUtil.prepareAndStart .
Logging is configured slightly differently during testing, where additional output is produced at the end of the test run and separate files are used. See TestLoggerFactory .
Reading logs
Configuration for the logging system can be found in log.xml . By default all messages with level INFO and above are written to the log file, idea.log . When running Studio locally, you can find it under tools/idea/system/log . Warnings are additionally written to standard output and errors are made visible to the user by flashing a red icon in the status bar. See the section below for details on how to use the DEBUG level.
When you start Studio from IntelliJ, the run configuration will open two tabs in the Run/Debug tool window: “Console” and “idea.log”. The former displays standard output (and thus all warnings), the latter the full log (note that there’s UI there to filter displayed log entries).
Using loggers
Because loggers can be turned on and off in various ways, it‘s important to use a logger with a name that’s related to the code that’s using it (logger names typically come from class and package names). There are three ways of getting a Logger instance:
- Calling Logger.getInstance(Class) , the most common.
- From Kotlin, calling com.intellij.openapi.diagnostic.LoggerKt#logger() , e.g. val LOG = logger() .
- From Kotlin, calling com.intellij.openapi.diagnostic.LoggerKt#logger(KProperty) to be used in top-level functions.
If you are only logging in exceptional situations, consider constructing the Logger instance only once you need it, e.g. when dealing with an exception. The logging infrastructure has a cost, so this way you don‘t pay for what you don’t need. If you log during normal IDE operation (on INFO or DEBUG level), store the logger in a static final field, so it‘s not recreated every time it’s used. See go/adtstyle for more details.
Make sure to provide enough information and a Throwable instance when available. The idea.log file is often the only piece of information we get from users and it makes life a lot easier if it can be used to fix a problem that cannot be reproduced locally.
Pick the right level for every message. Scanning attached log files for errors and warnings is the first step in triaging a bug, so try not to spam these levels. Use the ERROR log level only in the case of genuinely unexpected errors. Error logs grab user’s attention since they flash a red icon in the status bar. In addition, the number of times these happen is tracked via metrics as a proxy for Studio quality. Typically, scenarios that you can recover from should not be errors. Exceptions logged as errors can be found in our exceptions dashboard.
Remember that formatting the strings and writing to the log file takes time, so consider using DEBUG level for any additional information (and see the section below on how to get that information back).
DEBUG level
By default DEBUG messages are not logged anywhere, but this doesn’t mean the level is useless. You (or the user) can turn on debug logging for a given logger (or all loggers in a given package) by using Help, Debug Log Settings. To use, paste name of a logger in the box and save your changes. You should start seeing relevant log output in idea.log . Remember that Logger.getInstance prepends a # character to the class name! When running Studio locally, you will have to change the display settings in the idea.log tab to show all levels (it shows only INFO and above by default). The set of enabled loggers is a sticky setting and will survive a restart. You can ask your users to go through this flow before attaching logs, to get additional information.
Remember that debug messages are ignored most of the time, so make sure not to do any work just for the purpose of logging (including calling String.format ). Most of the time, you should check Logger.isDebugEnabled before computing the information that needs to be logged. In Kotlin you can use the Logger.debug(e: Exception?, lazyMessage: () -> String) extension method which will do nothing if debug output is not needed.
Logcat

В Android SDK входит набор инструментов, предназначенных для отладки. Самый важный инструмент при отладке — это LogCat (очень красивое название, которое можно перевести как Логичный Кот). Он отображает сообщения логов (журнал логов), рассылаемые при помощи различных методов.
В студии версии Electric Eel обновили Logcat. Все старые примеры работают, но появились дополнительные возможности.
Рассмотрим на примере стандартное применение Logcat. Очень часто программисту нужно вывести куда-то промежуточные результаты, чтобы понять, почему программа не работает. Особо хитрые временно размещают на экране текстовую метку и выводят туда сообщение при помощи метода textView.setText(«Здесь был Васька»). Но есть способ лучше. В Android есть специальный класс android.util.Log для подобных случаев.
Класс android.util.Log позволяет разбивать сообщения по категориям в зависимости от важности. Для разбивки по категориям используются специальные методы, которые легко запомнить по первым буквам, указывающие на категорию:
- Log.e() — ошибки (error)
- Log.w() — предупреждения (warning)
- Log.i() — информация (info)
- Log.d() — отладка (degub)
- Log.v() — подробности (verbose)
- Log.wtf() — очень серьёзная ошибка! (What a Terrible Failure!, работает начиная с Android 2.2)
- Log.meow() — когда жрать дадут? (MEOW!) Недокументированный метод, используйте на свой страх и риск. Работает не на всех устройствах
В первом параметре метода используется строка, называемая тегом. Обычно принято объявлять глобальную статическую строковую переменную TAG в начале кода:
private val TAG = "MyApp"
private static final String TAG = "MyApp";
Некоторые в сложных проектах используют следующий вариант, чтобы понимать, в каком классе происходит вызов:
private val TAG = this.javaClass.simpleName
private static final String TAG = this.getClass().getSimpleName();
Далее уже в любом месте вашей программы вы вызываете нужный метод журналирования с этим тегом:
Log.i(TAG, "Это моё сообщение для записи в журнале");
Пользователи не видят журнал логов. Вы, как разработчик, можете увидеть его через программу LogCat, доступный в Android Studio.
Напишем простой пример с кнопкой.
package ru.alexanderklimov.flamingo import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() < private val TAG = this.javaClass.simpleName override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button: Button = findViewById(R.id.button) button.setOnClickListener < Log.i(TAG, "Кот нажал на кнопку") >> >
Запускаем программу и в студии открываем вкладку Logcat:

Вы увидите несколько строк с технической информацией.
--------- beginning of system --------- beginning of main --------------- PROCESS STARTED (25918) for package ru.alexanderklimov.flamingo --------------- 2023-05-24 16:31:08.294 25918-25961 OpenGLRenderer .
Если нажать на кнопку, то появится новая информация — наш приготовленный текст.
2023-05-24 16:51:57.482 25918-25918 MainActivity ru.alexanderklimov.flamingo I Кот нажал на кнопку
Обратите внимание, что по умолчанию в Logcat установлен фильтр package:mine . Это позволяет отсечь множество системных сообщений, которые вам не нужны. Вы можете удалить фильтр и увидеть все эти сообщения. Убедившись, что они вам действительно не нужны, верните фильтр обратно.
Фильтры можно настраивать по своему вкусу. Например, если у вас много категорий логов, то можете выбрать нужный. Просто начинайте вводить текст, подсказки будут вам помогать при вводе текста. Например, добавим ещё один фильтр.
package:mine level:info
Для нашего примера особо ничего не изменилось. Дело в том, что категория info включает в себя все остальные категории. Фильтр level:warn будет показывать только категории Warning и Error.
Кроме показа сообщений о своём приложении через фильтр package:mine можно установить фильтры для других приложений: package:package-ID (указать идентификатор)
Если вы установили много тэгов, то посмотреть только нужные можно через фильтр tag:. Тогда вы не увидите лишние записи, которые были по умолчанию.
package:mine tag:MainActivity
Можно убрать лишние записи через знак минуса. Например, уберём тэг OpenGLRenderer:
package:mine -tag:OpenGLRenderer
Все логи имеют временную метку. Можно использовать фильтр age с указанием интервала.
- age:30s — логи за последние 30 секунд
- age:2m — логи за последние 2 минуты
- age:1h — логи за последний час
- age:2d — логи за 2 дня
Кстати, все ваши фильтры запоминаются и хранятся в истории. Нажмите на значок слева от фильтра, чтобы увидеть полный список. У каждого фильтра есть крестик, позволяющий удалить фильтр из истории.

Слева в списке фильтров есть значок звёзды — вы можете поместить любимые фильтры в Избранное.
Есть и другие фильтры, а также возможность использовать регулярные выражения. Но на первых порах достаточно использовать базовые возможности.
В левой части Logcat есть различные значки. Один из них отвечает за внешний вид журнала логов: можно выбрать вариант Standard View или Compact View. Либо вы можете настроить под себя, выбрав Modify Views, тогда у вас откроется диалоговое окно с настройками.
Можно создавать несколько вкладок Logcat, нажимая на значок +.
Далее идёт текст к старой версии Logcat. Возможны некоторые разночтения с новой версией, но в целом всё работает.
Полный вид сообщения выглядит следующим образом.
03-09 20:44:14.460 3851-3879 / ru.alexanderklimov.cat I/OpenGLRenderer : Initialized EGL, version 1.4
- 03-09 20:44:14.460 Date/Time
- 3851-3879 Process & Thread IDs
- ru.alexanderklimov.cat Package name
- I/OpenGLRenderer Tag
- Initialized EGL, version 1.4 Message
Подобные длинные сообщения не всегда удобны для чтения. Вы можете убрать ненужные элементы. Для этого выберите значок LogCat Header в виде шестерёнки и уберите флажки у опций.

В LogCat вы можете отфильтровать сообщение по заданному типу, чтобы видеть на экране только свои сообщения. Для этого выберите нужный тип тега из выпадающего списка Verbose.
Типы сообщений можно раскрасить разными цветами через настройки File | Settings | Editor | Colors Scheme | Android Logcat.
Для отслеживания сообщений с заданным текстом введите в поле поиска нужную строку и нажмите Enter.
Также активно используйте варианты из других выпадающих списков. Например, выбирайте свой пакет из второй колонки, а в последней выбирайте Show only selected application. Для более точной настройки используйте Edit Fiter Configuration.

По умолчанию, окно LogCat выводится в нижней части студии. При желании, можно выбрать другие варианты через значок настроек окна.
LogCat также можно запустить из командной строки:
adb logcat
Параметры командной строки смотрите в документации.
Быстрое отключение журналирования
Настоятельно рекомендуется удалять все вызовы LogCat в готовых приложениях. Если проект очень большой и вызовы журналирования разбросаны по всем местам кода, то ручное удаление (или комментирование) становится утомительным занятием. Многие разработчики используют следующую хитрость — создают обёртку вокруг вызова методов LogCat.
public static final boolean isDebug = false; public final String TAG = "MyLogger"; public void MyLogger(String statement) < if (isDebug) < Log.v(TAG, statement); >>
Теперь остаётся только присвоить нужное значение переменной isDebug перед созданием готового apk-файла для распространения.
Способ устарел. В 17-й версии Android Build Tools появился класс BuildConfig, содержащий статическое поле DEBUG. Можно проверить следующим образом:
if (BuildConfig.DEBUG) < // Режим отладки, ведём логи >
Способ для продвинутых — например, требуется релиз с выводом в лог, или наоборот — debug с выключенным выводом. В этом случае можно создать собственный параметр и добавить его в секцию buildType gradle-файла:
buildTypes < release < // Здесь настройки релиза buildConfigField "boolean", "USE_LOG", "false" >debug < buildConfigField "boolean", "USE_LOG", "true" >// «Релиз с логами» наследуем от обычного релиза releaseWithLog.initWith(buildTypes.release) releaseWithLog < buildConfigField "boolean", "USE_LOG", "true" >>
В этом случае конфигурация releaseWithLog будет являться релизной сборкой с ведением логов. Естественно, в коде слегка поменяется проверка:
if (BuildConfig.USE_LOG) < // Здесь используем логи >
LogCat на устройстве
Попался в сети пример для просмотра сообщений LogCat на устройстве. С примером не разбирался, оставлю здесь на память.
Разметка для элемента списка:
Добавляем разрешение в манифест:
package ru.alexanderklimov.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class TestActivity extends ListActivity < private LogStringadapter adapter = null; private ArrayListlogarray = null; private LogReaderTask logReaderTask = null; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); logarray = new ArrayList(); adapter = new LogStringadapter(this, R.id.txtLogString, logarray); setListAdapter(adapter); logReaderTask = new LogReaderTask(); logReaderTask.execute(); > @Override protected void onDestroy() < logReaderTask.stopTask(); super.onDestroy(); >@Override protected void onListItemClick(ListView l, View v, int position, long id) < super.onListItemClick(l, v, position, id); final AlertDialog.Builder builder = new AlertDialog.Builder( TestActivity.this); String text = ((String) ((TextView) v).getText()); builder.setMessage(text); builder.show(); >private int getLogColor(String type) < int color = Color.BLUE; if (type.equals("D")) < color = Color.rgb(0, 0, 200); >else if (type.equals("W")) < color = Color.rgb(128, 0, 0); >else if (type.equals("E")) < color = Color.rgb(255, 0, 0); ; >else if (type.equals("I")) < color = Color.rgb(0, 128, 0); ; >return color; > private class LogStringadapter extends ArrayAdapter < private Listobjects = null; public LogStringadapter(Context context, int textviewid, List objects) < super(context, textviewid, objects); this.objects = objects; >@Override public int getCount() < return ((null != objects) ? objects.size() : 0); >@Override public long getItemId(int position) < return position; >@Override public String getItem(int position) < return ((null != objects) ? objects.get(position) : null); >public View getView(int position, View convertView, ViewGroup parent) < View view = convertView; if (null == view) < LayoutInflater vi = (LayoutInflater) TestActivity.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.logitem, null); >String data = objects.get(position); if (null != data) < TextView textview = (TextView) view .findViewById(R.id.txtLogString); String type = data.substring(0, 1); String line = data.substring(2); textview.setText(line); textview.setTextColor(getLogColor(type)); >return view; > > private class LogReaderTask extends AsyncTask < private final String[] LOGCAT_CMD = new String[] < "logcat" >; private final int BUFFER_SIZE = 1024; private boolean isRunning = true; private Process logprocess = null; private BufferedReader reader = null; private String[] line = null; @Override protected Void doInBackground(Void. params) < try < logprocess = Runtime.getRuntime().exec(LOGCAT_CMD); >catch (IOException e) < e.printStackTrace(); isRunning = false; >try < reader = new BufferedReader(new InputStreamReader( logprocess.getInputStream()), BUFFER_SIZE); >catch (IllegalArgumentException e) < e.printStackTrace(); isRunning = false; >line = new String[1]; try < while (isRunning) < line[0] = reader.readLine(); publishProgress(line); >> catch (IOException e) < e.printStackTrace(); isRunning = false; >return null; > @Override protected void onCancelled() < super.onCancelled(); >@Override protected void onPreExecute() < super.onPreExecute(); >@Override protected void onPostExecute(Void result) < super.onPostExecute(result); >@Override protected void onProgressUpdate(String. values) < super.onProgressUpdate(values); adapter.add(values[0]); >public void stopTask() < isRunning = false; logprocess.destroy(); >> >
Создание apk-файла в Android Studio
Конечной целью любой java-разработки является создание завершенного приложения : это может быть как библиотека/исполняемый jar-файл, либо web приложение. Имеются различные типы приложений и библиотек. При всем многообразии возможных разношёрстных типов готовых библиотек и приложений android-устройства выбиваются из общей колеи. Для android-устройств конечным программным продуктом являются apk-файлы, которые можно свободно распространять между пользователями.
На заре развития программного обеспечения вся разработка для android-устройств осуществлялась, как правило, в IDE Eclipse со специализированными плагинами типа ADT (Android Development Tools). Данная среда разработки позволяет создавать для android apk-файлы. Но времена быстро меняются, и сегодня гораздо эффективнее и быстрее создавать apk-файлы в представленной ещё в 2013 году Android Studio, основанную на старом конкуренте Eclipse — системе IntelliJ IDEA.
Аббревиатура apk (Android Package Kit) символизирует формат файлов, которые используются для распространения и установки приложений на устройства android. Файл apk содержит все необходимые элементы для правильной установки приложения на устройстве, и, по своему назначению, чем-то похож на исполняемые exe-файлы в Windows. Когда Вы «заходите в магазин» Google Play, чтобы выбрать и загрузить какое-либо приложение, Ваше устройство android скачивает и устанавливает файл apk с нужным приложением.
Создание apk-файла
Рассмотрим процесс создания apk-файла на примере p13osgi, в котором использовался OSGi-фреймворк. Этот пример подробно рассмотрен на странице Android и OSGI-фреймворк Felix. В данной статье используем готовый модуль из проекта.
Заметка. Почему в качестве примера создания apk-файла выбираем данный модуль/проект, а не какой-либо другой? Дело в том, что в данном примере используется расположенная в поддиректории lib внешняя библиотека. И для нас интерес будет представлять структура apk-файла с внешней jar-библиотекой : какое место в данном пакете будет занимать внешний файл org.apache.felix.framework-6.0.3.jar. Здесь следует понимать, что OSGi-фреймворк (Felix) позволяет создавать модульную структуру приложения. Причем, в режиме run-time можно динамически подключать новые модули (bunlde), останавливать запущенные модули, одновременно подключать разноверсионные модули. Данный функционал OSGi-фреймворка на примере Вы можете реально проверить на своем компьютере; для этого необходимо познакомиться с Уроком 8.
Создание APK-файлов всех модулей проекта
Чтобы использовать самый простой способ создания apk-файла, выберите в Android Studio пункт меню «Build → Build Bundle(s)/APK(s) → APK(s)», как это представлено на следующем скриншоте.

В данном случае для всех модулей проекта будут созданы apk-файлы. Здесь необходимо отметить, что apk-файлы будут без цифровой подписи и распространению не подлежат. Но на них можно «посмотреть», что мы и сделаем в последнем разделе статьи, а также можно проверить работоспособность на android-устройстве. Загрузку apk-файла на android-устройство мы рассмотрим в ближайшее время отдельной статьей. Также отдельной статьей я представлю процесс создания apk-файла с цифровой подписью при выборе пункта меню «Build → Generate Signed Bundle/APK».
А сейчас Вы должны увидеть, что для всех модулей проекта создаются apk-файлы, которые располагаются в поддиректориях проекта [project_name]/[module_name]/build/outputs/apk/debug/. Т.е. в поддиректории модуля build/outputs/apk/debug/ будет размещаться созданный apk-файл, наименование которого включает наименование модуля с постфиксом «-debug». В нашем примере будет создан файл p13osgi-debug.apk.
Определение типа apk : debug-release
Постфикс «-debug», добавляемый к наименованию пакета, определен по умолчанию. Вы можете самостоятельно переименовать файл, и он останется работоспособным. Но можно и изменить настройки. Для этого необходимо указателем мыши нажать на расположенную в левом нижнем углу маленькую кнопочку, как это представлено на нижнем левом скриншоте. Данная кнопка открывает окно со специальными ярлыками различных вспомогательных окон. При простом наведении указателя мыши на эту кнопку, появляется список всех этих окон для быстрого выбора нужного.
Откроем окно Build Variants и в дополнительно открытом окне (скриншот справа) найдем модуль p13osgi (наш пример).
Если в выпадающем списке переключить режим сборки с debug на release, то будет создаваться пакет p13osgi-release-unsigned.apk в поддиректории «build/outputs/apk/release/».
![]() |
![]() |
Создание APK-файла одного модуля проекта
Для того, чтобы создать apk-файл одного модуля, необходимо открыть панель Gradle (см.ярлык на скриншоте сверху слева). В открывшемся окне, как это представлено на следующем скриншоте, необходимо выбрать пункт меню «module_name → Tasks → build → build». В результате данных действий будет создан apk-файл только одного модуля.

Структура файла APK
В заключении посмотрим на внутренности нашего apk-файла. Сразу же отмечу, что apk-файл можно открыть zip-архиватором, например 7-Zip. Но многое останется недоступным. Лучше использовать анализатор apk-файлов от Android Studio. Далеко ходить не надо : необходимо выбрать пункт меню «Build → Analyze APK . » (см. самый верхний скриншот). В открывшемся диалоговом окне найти нужный пакет в файловой структуре, после чего в IDE будет открыта панель, как это представлено на следующем скриншоте.

Интерфейс панели анализатора разделен на 2 части. В верхней части Вы видите корневую структуру apk-файла. В нижней части можно просматривать структуру выделенного элемента верхней части.
Что сразу же бросается в глаза? Вспоминаем : в нашем примере/модуле была использована внешняя библиотека с OSGi-фреймворком Felix org.apache.felix.framework-6.0.3.jar, расположенная в поддиректории lib
В структуре созданного пакета поддиректория lib. Все файлы внешней jar-библиотеки размещаются в корне по пакетам. Можно предположить, что и дополнительное использование бандлов/модулей (а для чего использовать фреймворк, если не использовать бандлы) приведет к тому, что и их содержимое также будет интегрировано в общий пакет. Таким образом, мы лишаемся преимуществ использования OSGi-технологии при разработке приложений для android-устройств, поскольку любая доработка отдельного модуля/бандла будет связана с обновлением всей сборки (apk-пакета). Кроме этого, отсутствует возможность одновременного использования разноверсионных бандлов, а межмодульное взаимодействие посредством сервисов становится «слишком дорогим» (можно и напрямую постучаться к классам бандла, зачем нам посредник-активатор). На данном простом примере я не вижу преимуществ использования OSGi для создания многомодульного приложения.
Буду признателен всем, кто опровергнет данное предположение и предложит значимое использование OSGi-технологии в android-устройстве.
Что касается *.class’ов, то их также не будет в apk-файле. Им на смену пришли файлы *.dex .
Файл .dex
«Рабочей лошадкой» в системе Android является Dalvik Virtual Machine, не использующая байт-код Java. Виртуальная машина Dalvik является службой приложения, которая интерпретирует скомпилированный код в dex-файле. Инструкции байт-кода формата DEX не совпадают с инструкциями байт-кода Java. Таким образом, в apk-файле Java-классы представлены в формате .dex. Но необходимо отметить, что структура пакетов сохраняется.
Logcat
Наверное, самый базовый инструмент, который используют Android разработчики и QA специалисты при работе с Android.
В ходе написания кода разработчики выводят в консоль промежуточные результаты работы приложения в виде текстовых строк. Обычно здесь указывается информация о том, в какой момент и что делает приложение. За вывод этих данных отвечает встроенный журнал событий — Logcat.
С помощью Logcat можно узнать, какие запросы уходили на бэкенд, что отвечал бэкенд, какие данные сохранялись в базу данных и многое другое.
Самое главное, что дает Logcat — выводит стэк вызовов функций, в случае если произошла ошибка и приложение упало. Обычно имменно этот стэк вызовов копируется и вместе с условиями воспроизведения вставляется в баг репорт.
Если вы впервые слышите про Logcat и не понимаете, как читать из него данные, самый простой выход — скачать Android Studio, включить “Режим разработчика” на своем тестовом телефоне и подключить по USB девайс к вашему ПК. В Android Studio снизу вы увидите вкладку Logcat, которую надо будет открыть, а потом выбрать девайс и приложение, которое вы тестируете.
Приятный бонус заключается в том, что Logcat можно настроить под задачу: это позволяет делать вкладка “Уровень логгирования”, где можно отслеживать, например, только ошибки. А также можно выводить информацию в журнал по ключевым словам с помощью регулярных выражений.
Стоит упомянуть, что здесь вам также пригодятся знания adb, ведь события из Logcat можно быстро собрать, прописав в консоли “adb logcat”. Приятный бонус!
Однако есть небольшой нюанс: как вы, вероятно, знаете, приложение может быть собранно в друх видах:
“debug” (для тестирования и разработки) и “release” (для релизов в маркет и поставки приложения конечному пользователю).
Важно учитывать, что если приложение находится в “release” сборке, то Logcat не будет иметь доступ к процессу приложения (в соответствии с требованиями безопасности маркетплейса), если не установлены специальные флаги, позволяющие это обойти. В связи с чем и журнал пользовательских логов для такого приложения будет недоступен.
Подводя итог, можно сказать, что Logcat — это самый полезный повседневный инструмент. Logcat поможет понять, когда в приложении что-то идет не так. Весь ход выполнения программы отражен в логах и вам как QA инженеру не обязательно знать языки программирования, чтобы понять, что бизнес требования не соответствуют ожидаемому поведению приложения. Чем больше вы будете знать свое приложение, тем больше профита будет приносить чтение логов. А по стэку ошибки вы сможете “ставить диагноз” эффективнее и давать больше полезной информации в баг репорте.
А в следующей части мы поговорим про особенности сборки Android приложений и как работать с обфусцированными логами.
Как пользоваться Android Studio


Арина Мурашева Эксперт в Java, Kotlin, Android, SQL, проектировании информационных систем.
Android-разработчица такси Maxim и ментор курса «Android-разработчик» Арина Мурашева подробно рассказывает, как установить и использовать Android Studio и как собирать и отлаживать приложения.

Освойте профессию «Android-разработчик»
Для чего используется Android Studio?
Android Studio — это IDE (интегрированная среда разработки) для работы с платформой Android. Она позволяет разрабатывать приложения для смартфонов, планшетов, часов, телевизоров и других устройств на этой ОС. Я использую Android Studio, потому что это официальная среда разработки, которую поддерживает Google. Она основана на IntelliJ IDEA от компании JetBrains, чьи продукты я люблю и использую еще со студенческих времен. В Android Studio те же горячие клавиши и интерфейс, что и в других продуктах JetBrains, поэтому для меня эта среда самая привычная и удобная.
Установка Android Studio
16 месяцев
Android-разработчик
Запускайте приложения и игры для Android
4 391 ₽/мес 7 983 ₽/мес

1. Установка Java SDK
Установите Java SDK независимо от того, планируете вы разрабатывать на Java или Kotlin. Для этого перейдите на официальный сайт Oracle в раздел Downloads и скачайте нужную версию Java SDK. Для разных проектов могут понадобиться разные версии, но если вы не знаете, какая нужна, — скачивайте последнюю.
2. Установка и настройка Android Studio
В отличие от многих инструментов разработки, за Android Studio не нужно платить. Чтобы скачать Android Studio, перейдите на официальный сайт для разработчиков Android и нажмите Download, согласитесь с условиями использования и нажмите Download Android Studio. После завершения скачивания запустите установочный файл и начните процесс установки. Сначала выберите путь установки Android Studio и Android SDK. Оставьте пути по умолчанию или выберите свои.
Если у вас уже установлена старая версия Android Studio, то первое окно установщика будет выглядеть как на скриншоте ниже. При этом процесс установки будет немного отличаться, однако в этой статье рассматривается только первичная установка Android Studio.
После этого несколько раз нажмите Next, оставляя все параметры по умолчанию, пока не начнется установка. После завершения установки Android Studio должна запуститься автоматически. Если нет, то ярлык программы вы сможете найти в меню «Пуск» или на рабочем столе. При первом запуске Android Studio нужно будет ее настроить. Сначала студия спросит, нужно ли импортировать настройки с прошлой версии. Так как это первая установка студии, то сохраненных настроек у вас нет. Оставьте второй вариант и нажмите OK.
После этого завершите настройку и скачайте необходимые компоненты с помощью Setup Wizard, который открывается после нажатия OK в предыдущем окне.
Нажмите Next и перейдите к выбору типа установки компонентов Android Studio.
Если вам не нужна кастомная настройка компонентов, выберите Standard и нажмите Next. После этого установщик сообщит, что необходимо загрузить несколько компонентов для завершения установки. Нажмите Finish и подождите, пока все компоненты загрузятся и распакуются. После завершения этого процесса снова станет доступна кнопка Finish. Нажмите на нее, после чего появится экран приветствия Android Studio. 

Станьте Android-разработчиком — работайте в штате, на фрилансе или запускайте собственные приложения
Как использовать Android Studio
Работа в Android Studio похожа на работу в большинстве современных IDE. Однако, как и везде, здесь есть свои нюансы. Далее мы разберем основы работы в Android Studio. Для начала необходимо создать проект в Android Studio. На приветственном экране нажмите Create New Project, после этого вы увидите экран с шаблонами устройств и Activity (это класс, в котором реализуют логику экрана приложения). Для начала можно выбрать Phone and Tablet (телефоны и планшеты) и No Activity либо Empty Activity. Разница в том, что в первом случае вам нужно будет реализовать первую Activity с нуля, а во втором студия самостоятельно создаст готовый редактируемый шаблон. После выбора нажмите Next и увидите окно настроек будущего проекта. Название проекта (Name) в Android Studio может быть любым и даже содержать пробелы. А вот имя пакета (Package Name) должно быть уникальным, если вы собираетесь опубликовать приложение в Google Play. Что еще можно выбрать: расположение проекта (Save Location), язык (Language), который вы собираетесь использовать (Java или Kotlin), и минимальную поддерживаемую SDK (Minimum SDK). Минимальная поддерживаемая SDK — это самая ранняя версия операционной системы Android, в которой приложение может работать. Если вы меняете расположение файлов проекта, то не забудьте создать папку, которая будет содержать ваш проект. Обратите внимание, что в названии не должно быть пробелов. Язык здесь можно выбрать любой, потому что в проекте доступны и Java, и Kotlin. А вот минимальную поддерживаемую Android SDK выбирайте внимательно. Студия подсказывает, какое количество устройств на сегодняшний день поддерживают ту или иную SDK. Старайтесь выбрать минимальное значение, чтобы как можно больше устройств могли успешно работать с вашим приложением в Android Studio. Но учтите, что чем ниже минимальная SDK, тем больше трудностей будет возникать при разработке.
Структура проекта Android

Если в предыдущем шаге вы выбрали шаблон Empty Activity, то при создании проекта студия сгенерирует и структуру файлов проекта. Так выглядит пустой, только что созданный проект в Android Studio. Он содержит 2 корневые папки: app и Gradle Scripts. Папка app включает 3 подпапки: manifests (содержит файлы конфигураций приложения), java (содержит исходный код приложения) и res (содержит файлы ресурсов — картинок, стилей, размерностей и т.д.). AndroidManifest.xml в папке manifests содержит информацию о пакетах и компонентах приложения. Этот файл важен для работы приложения Android, так как именно в нем прописаны разрешения приложения на использование компонентов системы Android. Также в нем определяется, как будут запускаться компоненты приложения.
Читайте также Кто такой Android-разработчик?
- Папка drawable содержит файлы с изображениями.
- В папке layout нужно располагать xml-файлы, используемые для создания интерфейса приложения.
- Папка mipmap хранит значки приложения.
- Папка values хранит xml-файлы со значениями строк, цветов, тем, стилей.
Папка Gradle Scripts содержит скрипты для автоматизации сборки проекта.
Папка .idea не видна на скриншоте, но если изменить конфигурацию Android на Project, то она появится. Эта папка нужна для настройки метаданных проекта в Android Studio.
Редактор xml
Для редактирования xml-файлов в Android Studio встроен удобный инструмент. Он позволяет не только редактировать код xml-файлов, но и видеть изменения в режиме реального времени с помощью визуального представления. В этом же визуальном представлении можно редактировать xml-файлы.
Чтобы посмотреть работу этого редактора, откройте файл activity_main.xml, сгенерированный Android Studio. Кстати, если ваш проект уже разросся и искать файлы неудобно, то нажмите клавишу Shift быстро два раза, и откроется окно поиска по файлам проекта. Начните вводить туда название нужного файла, а затем выберите его из списка. Как видно на анимации, необязательно вводить слова полностью — достаточно первых букв.
По умолчанию открывается только редактор кода.

Чтобы открыть визуальный редактор, нажмите кнопку Split в верхнем правом углу, чтобы отобразить оба представления рядом. Или кнопку Design, чтобы открыть только визуальное представление.
Gradle
Android Studio выполняет сборку приложения с использованием системы Gradle. Он значительно упрощает сборку проекта из большого количества файлов в apk-файл, который можно установить на Android-устройстве.
Хочу поделиться лайфхаком, который выручал меня не раз. Если проект перестал собираться по непонятной причине, скорее всего, это связано с gradle. В таком случае в меню выберите Build, а затем опцию Clear Project.
Сборка и отладка приложения
После того как вы добавили первую функциональность в свое приложение, начните отлаживать его (запускать и проверять работоспособность всех функций). Лучше делать это на устройстве Android.
Для этого подключите устройство Android к компьютеру через USB. При этом убедитесь, что на телефоне включена отладка по USB в параметрах разработчика.
Чтобы включить параметры разработчика, в настройках своего телефона найдите пункт «Номер сборки» (обычно находится в «Сведениях об устройстве») и нажмите на него быстро семь раз. Далее перейдите в параметры разработчика и включите отладку по USB.
После этого подключите телефон через USB к компьютеру и увидите название своего устройства в верхней панели Android Studio — у меня это Samsung. Обратите внимание, на телефоне могут появиться уведомления, где нужно разрешить отладку с данного компьютера.

Затем нажмите на кнопку Run (зеленый треугольник), и приложение запустится на вашем телефоне.
Если приложение «упало» (завершило работу, когда не должно было) или возникли какие-то другие ошибки — данные вы увидите на вкладке Logcat (внизу).

В панели настроек Logcat можно выбрать устройство, на котором производится отладка, отлаживаемый процесс и поставить фильтр на сообщения, которые хотите видеть в Logcat. Обычно сообщения об ошибках и так заметны — они выделяются красным, — но если хотите видеть только их, то поставьте фильтр Error.

Отладка приложения на виртуальных устройствах
Устройств на Android так много, что невозможно протестировать код на каждом из них. Здесь на помощь приходят виртуальные устройства, доступные для скачивания из Android Studio.
Чтобы создать виртуальное устройство, откройте AVD Manager (Android Virtual Device Manager) и начните создание желаемого устройства.

Для создания нового устройства нажмите кнопку Create Virtual Device. Затем выберите устройство (модель телефона).
После нажмите Next и переходите к выбору системы Android, которая будет установлена на устройство. Если ранее вы не устанавливали ни одной эмулированной системы, то ее нужно будет скачать. У меня уже скачан Android Q.
После скачивания нажмите Next, затем Finish, и создание виртуального устройства завершено.
Чтобы запустить приложение на созданном устройстве, выберите его в списке устройств и нажмите кнопку Run.
Главное — практика
По-настоящему освоить Android Studio получится только самостоятельно в процессе практики. Дополнительно рекомендую изучить горячие клавиши в Android Studio (как двойное нажатие Shift для поиска по файлам).
Android-разработчик
Освойте программирование на Java и Kotlin, мобильную разработку и UX/UI, разработайте свое приложение для Android. Центр карьеры поможет с резюме и подготовкой к собеседованию. Программа подойдет для новичков
How to find the logs on Android Studio?
I have tried to import my project to Android Studio and I got this error. I need to know where I can get the logs.
Consult IDE log for more details (Help | Show Log)
18.9k 31 31 gold badges 68 68 silver badges 75 75 bronze badges
asked Nov 5, 2013 at 8:49
5,243 6 6 gold badges 48 48 silver badges 65 65 bronze badges
Did you try View > Tool Windows > Android?
Nov 5, 2013 at 8:51
There is an option in your Toolbar to check your logs by enabling (DDMS i.e. android icon) or else in bottom you can check Android>>Devices | logcat.
Nov 5, 2013 at 9:00
@PankajKumar I want to know where to find logs.how this question will be duplicate?
Nov 5, 2013 at 9:02
@Gru it doesnot show anything about y this project has not been integrated?
Nov 5, 2013 at 9:05
In my Windows 10 «Help/Show Log In Explorer» goes to «This Computer» view and it does not go to the directory where the logs are. The logs can be found manually in C:\Users\
Apr 6, 2018 at 6:03
17 Answers 17
On toolbar -> Help Menu -> Show log in Explorer or Show log in Finder (for Mac users).
It opens log folder, where you can find all logs.

answered Nov 6, 2013 at 10:26
Gabriele Mariotti Gabriele Mariotti
334k 101 101 gold badges 921 921 silver badges 859 859 bronze badges
@Alston is it a good reason to downvote an answer of 3 years ago? In 2.2.3 the Help is in the same position. Check the toolbar, last entry on the right «Help» then «show log in explorer».
Jan 17, 2017 at 12:20
For mac users, that would be Show Log in Finder
Jan 3, 2018 at 12:44
I got the same error, however the log shows no valuable information yet: 2021-12-07 14:32:10,627 [ 156388] ERROR — intellij.openapi.progress.Task — OS: Linux 2021-12-07 14:32:10,628 [ 156389] ERROR — intellij.openapi.progress.Task — Last Action: 2021-12-07 14:32:10,722 [ 156483] INFO — cState$SyncStateUpdaterService — stopTrackingTask(RESOLVE_PROJECT:0) 2021-12-07 14:32:10,726 [ 156487] WARN — e.project.sync.GradleSyncState — Gradle sync failed: Sync failed: reason unknown (55 s 334 ms)
Dec 7, 2021 at 11:36
It works only if you have some project opened (at least it’s true for my Android Studio Chipmunk | 2021.2.1 Patch 2), so you have to open some project or create at least blank project first
Logcat
Наверное, самый базовый инструмент, который используют Android разработчики и QA специалисты при работе с Android.
В ходе написания кода разработчики выводят в консоль промежуточные результаты работы приложения в виде текстовых строк. Обычно здесь указывается информация о том, в какой момент и что делает приложение. За вывод этих данных отвечает встроенный журнал событий — Logcat.
С помощью Logcat можно узнать, какие запросы уходили на бэкенд, что отвечал бэкенд, какие данные сохранялись в базу данных и многое другое.
Самое главное, что дает Logcat — выводит стэк вызовов функций, в случае если произошла ошибка и приложение упало. Обычно имменно этот стэк вызовов копируется и вместе с условиями воспроизведения вставляется в баг репорт.
Если вы впервые слышите про Logcat и не понимаете, как читать из него данные, самый простой выход — скачать Android Studio, включить “Режим разработчика” на своем тестовом телефоне и подключить по USB девайс к вашему ПК. В Android Studio снизу вы увидите вкладку Logcat, которую надо будет открыть, а потом выбрать девайс и приложение, которое вы тестируете.
Приятный бонус заключается в том, что Logcat можно настроить под задачу: это позволяет делать вкладка “Уровень логгирования”, где можно отслеживать, например, только ошибки. А также можно выводить информацию в журнал по ключевым словам с помощью регулярных выражений.
Стоит упомянуть, что здесь вам также пригодятся знания adb, ведь события из Logcat можно быстро собрать, прописав в консоли “adb logcat”. Приятный бонус!
Однако есть небольшой нюанс: как вы, вероятно, знаете, приложение может быть собранно в друх видах:
“debug” (для тестирования и разработки) и “release” (для релизов в маркет и поставки приложения конечному пользователю).
Важно учитывать, что если приложение находится в “release” сборке, то Logcat не будет иметь доступ к процессу приложения (в соответствии с требованиями безопасности маркетплейса), если не установлены специальные флаги, позволяющие это обойти. В связи с чем и журнал пользовательских логов для такого приложения будет недоступен.
Подводя итог, можно сказать, что Logcat — это самый полезный повседневный инструмент. Logcat поможет понять, когда в приложении что-то идет не так. Весь ход выполнения программы отражен в логах и вам как QA инженеру не обязательно знать языки программирования, чтобы понять, что бизнес требования не соответствуют ожидаемому поведению приложения. Чем больше вы будете знать свое приложение, тем больше профита будет приносить чтение логов. А по стэку ошибки вы сможете “ставить диагноз” эффективнее и давать больше полезной информации в баг репорте.
А в следующей части мы поговорим про особенности сборки Android приложений и как работать с обфусцированными логами.
Services tool window
The Services tool window enables you to manage various services that help you during software development, such as run/debug configurations, application servers, database sessions, and Docker connections. Plugin developers can add other services through the IntelliJ platform API.

The main toolbar contains the following buttons and menus that are common for all service types:
Expand All Control+NumPad-+
Expand all items in the list.
Collapse All Control+NumPad—
Collapse all items in the list.
Choose how you want to organize the list of services:
- Service Type : arrange services by type, such as Run Dashboard , Docker , or Database
- Service Groups : arrange services by group, such as a build tool or a data source name
Choose how you want to filter the list of services.
Open in New Tab
Move the selected items to a separate tab.
Add Service Alt+Insert
Choose a service type to add.
Run/debug configurations
Run/debug configurations are not listed in the Services tool window by default. You need to explicitly specify the types of configurations you want to be available and create the corresponding configurations.
Add Run/Debug configurations to the Services window

- Select View | Tool Windows | Services from the main menu or press Alt+8 .
- In the Services tool window, click Add service , then select Run Configuration Type… .
- Select a run/debug configuration type from the list to add all configurations of this type to the window. Note that the tool window will only display the configuration types for which you have created one or more configurations.
Buttons on the toolbar depend on the selected type of the run/debug configuration and can include the following:
Run the selected configuration.
Debug Control Shift D
Run the selected configuration in Debug mode.
Stop the selected configuration.
Rerun the selected configuration.
Rerun in Debug Mode Control Shift D
Rerun the selected configuration in Debug mode.
Filter the output for the selected configuration. For example, you can select to show warnings and successful steps.
Additional actions related to the configuration. For example, you can open and modify the settings of the selected configuration.
Application servers
All types of application server run/debug configurations are available in the Services tool window by default. Create an application server configuration, and it will be available in the list of services.
Run the selected application server configuration.
Restart the selected application server configuration.
Debug Control Shift D
Debug the selected application server configuration.
Stop the selected application server configuration.
Deploy all artifacts of the selected application server configuration.
Configure which artifacts to deploy for the selected application server configuration.
Update Running Application Control+F10
Update a running application after modifying the source code.
Cloud providers
This type of service is available if you have configured the corresponding cloud provider settings.
Add a cloud provider
- Click , select Cloud Connection , and then select the necessary cloud provider.
- Configure the cloud provider connection settings and click OK to apply the new configuration.
Connect to the selected cloud provider.
Disconnect from the selected cloud provider.
Edit Configuration Shift+F4
Configure the selected cloud provider connection settings.
Deploy artifacts to the selected cloud provider.
Database service
In the database service, you can manage your sessions and connections. Connection is a physical communication channel and session is a state of information exchange. For example, if you surf a social network, your connection log might have thousands of connection entries between a client and a server while a session log might show you only a single log entry with the number of bytes transferred.
For more information about managing database sessions, refer to Sessions.

Left toolbar controls
Data sources
Action and shortcut
Jump to Query Console Control+Shift+F10
Open the Query Consoles popup. In the Query Consoles popup, you can select a query console that you want to open in the editor .
Close the database connection for the selected data source or data sources. (The data sources with connected sessions are indicated with a green dot in the corner of their icon.)
Sessions
Action and shortcut
Select the isolation level for database transactions and the way the transactions are committed.
- Auto : the current transaction is committed automatically when you submit your local changes to the database server.
- Manual : the changes submitted to the database server are accumulated in a transaction that can either be committed or rolled back explicitly by means of the Submit and Commit () or Roll Back () buttons on the toolbar.
For more information about database transaction modes and isolation, refer to Submit changes to a database.
(For the Manual transaction mode.) Commit the current transaction. This button is available only for the manual transaction mode. See also, transaction mode and isolation.
(For the Manual transaction mode.) Roll back changes. This button is available only for the manual transaction mode. See also, transaction modes and isolation.
Cancel Running Statements
Terminate execution of the current statement or statements.
Restore Default Layout
Restore default positions of visual elements in the tool window.
Context menu
Data sources
Action and shortcut
Jump to Query Console Control+Shift+F10
Open the Query Consoles popup. In the Query Consoles popup, you can select a query console that you want to open in the editor .
Close the database connection for the selected data source or data sources. (The data sources with connected sessions are indicated with a green dot in the corner of their icon.)
Close All Sessions
Close all opened sessions to a data source.
Open in New Tab
Move the selected items to a separate tab.
Open Each in New Tab
Split the selected items into separate tabs.
Open Each Type in New Tab
Create separate tabs for each type of service.
Close all opened sessions to a data source. Identical to Close All Sessions .
Sessions
Action and shortcut
Select the isolation level for database transactions and the way the transactions are committed.
- Auto : the current transaction is committed automatically when you submit your local changes to the database server.
- Manual : the changes submitted to the database server are accumulated in a transaction that can either be committed or rolled back explicitly by means of the Submit and Commit () or Roll Back () buttons on the toolbar.
For more information about database transaction modes and isolation, refer to Submit changes to a database.
(For the Manual transaction mode.) Commit the current transaction. This button is available only for the manual transaction mode. See also, transaction mode and isolation.
(For the Manual transaction mode.) Roll back changes. This button is available only for the manual transaction mode. See also, transaction modes and isolation.
Cancel Running Statements
Terminate execution of the current statement or statements.
Restore Default Layout
Restore default positions of visual elements in the tool window.
Rename Session Shift+F6
Display the Rename Session » dialog where you can specify a name for a session.
Close the selected session.
Open in New Tab
Move the selected items to a separate tab.
Open Each in New Tab
Split the selected items into separate tabs.
Open Each Type in New Tab
Create separate tabs for each type of service.
Close all opened sessions to a data source. Identical to Close All Sessions .
SQL files
Action and shortcut
Select the isolation level for database transactions and the way the transactions are committed.
- Auto : the current transaction is committed automatically when you submit your local changes to the database server.
- Manual : the changes submitted to the database server are accumulated in a transaction that can either be committed or rolled back explicitly by means of the Submit and Commit () or Roll Back () buttons on the toolbar.
For more information about database transaction modes and isolation, refer to Submit changes to a database.
(For the Manual transaction mode.) Commit the current transaction. This button is available only for the manual transaction mode. See also, transaction mode and isolation.
(For the Manual transaction mode.) Roll back changes. This button is available only for the manual transaction mode. See also, transaction modes and isolation.
Cancel Running Statements
Terminate execution of the current statement or statements.
Restore Default Layout
Restore default positions of visual elements in the tool window.
Attach the selected file to one of the available sessions. To detach the file from a session, open the file in the editor , click the list and select Detach Session .
Open in New Tab
Move the selected items to a separate tab.
Open Each in New Tab
Split the selected items into separate tabs.
Open Each Type in New Tab
Create separate tabs for each type of service.
Close all opened sessions to a data source. Identical to Close All Sessions .
Jump to Source F4
Open the file in the editor .
Docker
This type of service is available if you have configured connection settings for at least one Docker instance. For more information, refer to Connect to the Docker daemon.
Add a Docker connection
- Click and select Docker Connection .
- Configure the docker connection settings in the New Docker Connection dialog.
If you have Docker contexts configured, you can select Docker Connections from Docker Contexts to add the corresponding connections.
Main Docker node
These are the main actions for working with the selected Docker connection:
Connect to the Docker daemon and list all available images and containers.
Disconnect from the Docker daemon.
Edit the Docker connection settings.
Select an existing Docker run configuration or create a new one. For more information, refer to Docker containers
Delete the connection to the selected Docker daemon.
Pull an image from a Docker registry. For more information, refer to Pull a public image from Docker Hub.
Remove all stopped containers, unused volumes and networks, dangling images, and all build caches.
Containers
This node lists all containers managed by the corresponding Docker daemon.
Remove all stopped containers.
When you select a container, the following actions are available:
Run the selected container.
Stop the selected container.
Delete the selected container.
Container dashboard
The Dashboard tab provides important information about the selected container:
- Name and hash ID of the container. You can click the image name to highlight the image that was used to run the selected container.
- Names and values of environment variables defined in the container.
- Ports mappings between the container and the host.
- Volume bindings between the container and the host.
Click Add to add a new variable, port binding, or volume binding, and recreate the container.
Click to open a menu with some additional actions:
Open a tab with the log messages from the container’s standard output streams: STDOUT and STDERR .
For more information, refer to the docker logs command reference.
Open a tab with the file browser for the running container.
Select any file and click to open it remotely in the editor or click to create a copy of the file as a scratch.
The file browser may not work by default for containers that don’t have the full ls package (for example, images that are based on Alpine, Photon, and BusyBox). To use it, you can add the following command in the Dockerfile:
FROM alpine:3.10 RUN apk add coreutils
FROM photon:3.0 RUN echo y | tdnf remove toybox
Run docker inspect on the container and output it to a separate tab.
Copy the hash ID of the image used to run this container.
Copy Container ID
Copy the hash ID of the container.
Images
This node lists all images managed by the corresponding Docker daemon.
Pull an image from a Docker registry. For more information, refer to Pull a public image from Docker Hub.
Remove all unused images.
When you select an image, the following actions are available:
Create a Docker container from the selected image.
Remove the selected image.
Copy Docker Image
Copy an image from one Docker daemon to another. For more information, refer to Copy image to another Docker daemon.
Push an image to a Docker registry. For more information, refer to Push an image to a Docker registry.
Image dashboard
The Dashboard tab provides important information about the selected image:
- Name, hash ID, date of latest changes, and size of the image.
- List of tags that point to the image.
- List of existing containers created from this image.
It also includes some useful actions for the selected image:
Create a Docker container from the selected image.
Push an image to a Docker registry. For more information, refer to Push an image to a Docker registry.
Open a tab that shows the layers (intermediate internal untagged images) from which the selected image consists.
Click to open a menu with some additional actions:
Copy the hash ID of the selected image.
Run docker inspect on the selected image and output it to a separate tab.
Open a tab with the image’s labels.
Networks
This node lists all networks managed by the corresponding Docker daemon.
Create a Docker network for your containers to operate.
Remove all unused networks.
Network dashboard
The Dashboard tab provides important information about the selected network:
- Name and hash ID of the network.
- List of containers connected to this network.
- List of labels assigned to this network.
Click Inspect to run docker inspect on the selected network and output it to a separate tab.
Volumes
This node lists all volumes managed by the corresponding Docker daemon.
Create a Docker volume for your containers to use.
Remove all unused volumes.
When you select a volume, the following actions are available:
Remove the selected volume.
Volume dashboard
The Dashboard tab provides important information about the selected volume:
- Name or hash ID of the volume.
- List of containers that use this volume.
It also includes some useful actions for the selected volume:
Run docker inspect on the selected image and output it to a separate tab.
Remove the selected volume.
Click to open a menu with some additional actions:
Open a tab with the volume’s labels.
Main Docker Compose node
Deploy your selected Docker Compose services using the associated run/debug configuration. For more information, refer to Docker Compose
Stop all containers in the selected Docker Compose services.
Stop and remove all containers in the selected Docker Compose services, including all related networks, volumes, and images.
Edit the selected Docker Compose run configuration.
Choose whether you want to show or hide containers that are not running and images with no tags.
Docker Compose services
Start all containers for the selected service.
Stop all containers for the selected service.
Change the number of containers for the selected service.
Delete the selected container.
Choose whether you want to show or hide containers that are not running and images with no tags.
Kubernetes
This type of service is available if:
- The Kubernetes plugin is installed and enabled. For more information about the Kubernetes integration in IntelliJ IDEA, refer to Kubernetes.
- IntelliJ IDEA detects a Kubernetes cluster configuration file. By default, this is a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable. For more information about kubeconfig files, refer to Organizing Cluster Access Using kubeconfig Files.
By default, the Services tool window shows the current cluster context taken from the default kubeconfig file. You can add more contexts to this tool window.
Refresh information from the Kubernetes cluster.
Select a namespace to filter the resources available in the cluster.
New Kubernetes Contexts
Add a Kubernetes context as a node in the Services tool window.
In the opened file, the following actions are available:
- : Apply changes to the current context and namespace.
- : Delete the resource from the current context and namespace.
- : Reload the file content from the cluster
- : Show the differences between the opened file and the corresponding cluster resource in the diff viewer.
- : Change current context
Display detailed information about the selected resource, similarly to the kubectl describe command.
Remove the selected resource from the cluster.
Output the log of a container in the selected pod.
Save the log of a container in the selected pod to a scratch file and open it in the editor.
Instead of using a scratch file, you can set the path for saving logs or choose the location every time. To configure the download location for pod logs, click or open Settings | Build, Execution, Deployment | Kubernetes .
Attach to the console of the process running inside a container of the selected pod.
Run an interactive shell for the container in the selected pod.
By default, IntelliJ IDEA runs /bin/bash . To run a different shell, open Settings | Build, Execution, Deployment | Kubernetes and, in the Command to run shell inside container field, specify the shell that your pods use.
Forward one or more local ports to remote ports in a pod.
- 7070 — listen on local port 7070 and forward data to/from remote port 7070.
- :8080 — listen on a random local port and forward data to/from remote port 8080.
- 8888:5000 — listen on local port 8888 and forward data to/from remote port 5000.
Fore more examples on port forwarding, refer to the Kubernetes documentation.
Productivity tips
The Services tool window can include a lot of services, which you can group according to their type or create separate tabs for your own custom grouping. For example, you can create a tab that will include the following: the run configuration for the application that you are developing, the Docker container that runs the database used as a backend for your application, and a console for accessing the database.
Hide the services tree
Click in the right part of the Services tool window toolbar and then click Show Services Tree to remove the checkbox. You can also press Control+Shift+T to toggle the services tree.
If you hide the services tree, it is replaced by a services navigation bar. Press Alt+Home to focus the services navigation bar.
Hide, remove, and delete services
Right-click any service and select Delete Delete to completely remove the corresponding run configuration, cloud provider, Docker connection, and so on.
If you don’t want to show run/debug configurations of a certain type in the Services tool window, right-click the corresponding configuration and select Remove Configuration Type from Services . This will not remove the actual configuration.
To hide a specific run configuration from the Services tool window, right-click the corresponding configuration and select Hide Configuration . To see all hidden run configurations, click and select Restore Hidden Configurations .

