Logging in android studio

Логирование в Android Studio без кода

Вам больше не нужно ставить Log.d() в каждой строке кода!

Когда мы отлаживаем приложения, мы иногда начинаем плодить логи по всему коду, чтобы разобраться с какой-либо проблемой.

Это прекрасно работает, но бывает так, что мы забываем удалить логи перед тем как закоммитаться, и они «благополучно» попадают в продакшн код.

Хорошая практика — не оставлять логи для отладки после её завершения, даже если вы используете ProGuard для их автоматического удаления в скомпилированном коде, так как они оказывают пагубное влияние на общую читабельность вашего кода. Как и комментарии, логи могут легко начать расходиться с окружающим их кодом, в лучшем случае становясь бесполезными, а в худшем вводящими в заблуждение.

Ситуация усложняется, когда выведение логов требует соблюдения определённых условий. Теперь это не просто бесполезное нагромождение if else , но ещё и потенциально дорогостоящий код.

Но, оказывается, есть очень простой способ решения этой проблемы. IntelliJ и Android Studio позволяют создавать точки прерывания (англ. breakpoints), не прерывающие исполнение кода (да, это законно).

Сначала создайте точку прерывания на любой строке, либо щелкнув в левой части редактора, либо с помощью сочетания клавиш Ctrl-F8 . Затем вы можете отредактировать точку прерывания, либо щелкнув по ней правой кнопкой мыши, либо используя комбинацию клавиш Ctrl-Shift-F8 . Вы увидите такое окно:

Затем снимите флажок Suspend (рус. приостановить), и вы увидите больше параметров в этом модальном окне:

Теперь добавьте любые логи в поле Evaluate and log следующим образом:

Читайте также:  Звуки уведомлений для андроид короткие мр3

И после удаления всех логов из кода и добавления их в точки прерывания ваш код будет выглядеть чистым:

Гораздо лучше, правда? Теперь идите и используйте непрерывающиеся точки прерывания! Все, что вам нужно сделать, это запустить приложение в режиме отладки, и сообщения будут выводиться в консоль.

О других хитростях в Android Studio читайте здесь

Источник

Android LogCat And Logging Best Practice

android.util.Log is the log class that provides the log function. It provides the below methods to log data into the LogCat console.

1. Android Log Methods.

  1. Log.v(): Print verbose level log data. The verbose level is the lowest log level, if you print so much this kind of log data, it is not meaningful.
  2. Log.d(): Print debug level log data. Debug level is one step higher than verbose level. Debug log data is usually useful in android application development and testing.
  3. Log.i(): Print info level log data. Info level is one step higher than debug level. Info log data is used to collect user actions and behaviors.
  4. Log.w(): Print warn level log data. Warn level is one step higher than info level. When you see this kind of log data, it means your code exists potential risks, you need to check your code carefully.
  5. Log.e(): Print error level log data. Error level is the highest level. It is always used in java code catch block to log exception or error information. This kind of log data can help you to find out the root cause of app crashes.

2. Android Log Methods Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ciBUMesUfVo

  1. This example is very simple. When you click the button, it will print above 5 kinds of log data in the LogCat console.
  2. When you input the search keyword LogActivity in the LogCat panel, the app log data will be filtered out. For each line of log data, there are the log time, class name, and log message.
  3. You can also filter out the log data by it’s type, verbose, info, debug, warn, or error. This can make log data search more easily and accurately, you can see the below demo video.
Читайте также:  Создаем троян для андроид

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/zyUvmTF_Mzw

  1. Click the Settings icon in the LogCat panel, you can configure which column to be displayed for each line of the log.
  2. The columns include Show date and time, Show process and thread IDs(PID-TID), Show package name, Show tag, you can see it in the below picture.

Источник

Оцените статью