Disable logcat in android

Logcat

В Android SDK входит набор инструментов, предназначенных для отладки. Самый важный инструмент при отладке — это 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 в начале кода:

Некоторые в сложных проектах используют следующий вариант, чтобы понимать, в каком классе происходит вызов:

Далее уже в любом месте вашей программы вы вызываете нужный метод журналирования с этим тегом:

Также используется в исключениях:

Пользователи не видят этот журнал. Но, вы, как разработчик, можете увидеть его через программу LogCat, доступный в Android Studio.

Полный вид сообщения выглядит следующим образом.

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 также можно запустить из командной строки:

Читайте также:  Таймер для андроид студио

Параметры командной строки смотрите в документации.

Быстрое отключение журналирования

Настоятельно рекомендуется удалять все вызовы LogCat в готовых приложениях. Если проект очень большой и вызовы журналирования разбросаны по всем местам кода, то ручное удаление (или комментирование) становится утомительным занятием. Многие разработчики используют следующую хитрость — создают обёртку вокруг вызова методов LogCat.

Теперь остаётся только присвоить нужное значение переменной isDebug перед созданием готового apk-файла для распространения.

Способ устарел. В 17-й версии Android Build Tools появился класс BuildConfig, содержащий статическое поле DEBUG. Можно проверить следующим образом:

Способ для продвинутых — например, требуется релиз с выводом в лог, или наоборот — debug с выключенным выводом. В этом случае можно создать собственный параметр и добавить его в секцию buildType gradle-файла:

В этом случае конфигурация releaseWithLog будет являться релизной сборкой с ведением логов. Естественно, в коде слегка поменяется проверка:

LogCat на устройстве

Попался в сети пример для просмотра сообщений LogCat на устройстве. С примером не разбирался, оставлю здесь на память.

Источник

www.androidpolice.com

Follow Android Police

Stop Log Can Disable All Android Logs On Your Device For Enhanced Privacy And Performance (Root Only)

All the apps on your phone feed log data into the Android logcat, but maybe you don’t want the log to have all that information about what you’re doing on the phone. If you’re rooted, a new app from Wanam can help. Stop Log disables all Android loggers at the system level.

Image Gallery (1 Images)

The most obvious benefit is privacy, if that’s the sort of thing you’re worried about. On unrooted devices, apps are only able to see their own logcats. However, the logcat can be accessed with ADB, assuming someone has physical access to your device. No log, no sensitive data, right? The developer also claims that disabling logging will improve performance, but that depends on how much data is being dropped into the log. Your mileage may vary on that one, but beware confirmation bias.

You have a bit of control over which logs are blocked with Stop Log—any combination of main, radio, event, and system logs can be killed. Stop Log should work on any rooted Android device running Android 4.3 or higher.

Android gaming is getting ready to compete

Ryan is a tech/science writer, skeptic, lover of all things electronic, and Android fan. In his spare time he reads golden-age sci-fi and sleeps, but rarely at the same time. His wife tolerates him as few would. He’s the author of a sci-fi novel called The Crooked City, which is available on Amazon and Google Play.

Источник

Disable logcat in android

Многие владельцы Android хотят иметь систему настроенную под себя, со своим оформлением, но далеко не у всех получается с первого раза и все приходится делать заново, не узнав причину, ведь причина может быть самая элементарная: забыли добавить файл, ошиблись в каком то файле и случайно добавили лишний символ, а ведь если вы делали по большой инструкции, несколько часов или дней (в связи такой сложностью, у вас редко бывает время или вы не понимали на тот момент как надо было делать), а у вас ваше приложение не заработало, как-же быть тогда?
Есть одно решение, воспользоваться логом системы — LogCat.
Пользоваться им не очень сложно и делается он запросто, для начала нам необходимо скачать программу ADB, скачать вы её можете — здесь. Распаковываем скачанный архив в папку C:/adb. Открываем командную строку и пишем

Читайте также:  Лучший самоучитель английского языка для андроид

и открываем ваше нерабочее приложение, если это статус-бар, то ждём когда он выдаст ошибку. В папке C:/adb будет лежать logcat.txt, его вы вылаживаете сюда или отправляете человеку, который вас попросил, ждёте ответа.

P.S. Тема была специальна создана, дабы всё время не описывать и объяснять, что да как делать.

Сообщение отредактировал WinKarbik — 14.08.14, 16:00

Там есть информация об этом, но возможно не так подробно.

Имеет смысл не распыляться по темам, а написать там, и попросить добавить в шапку той темы.

WinKarbik,

в этом случае, тема просто погрязнет в мусоре других тем, вот и всё.
Та же тема всегда наверху в том разделе.

Источник

How to Fix “Android studio logcat nothing to show” in Android Studio?

Logcat Window is the place where various messages can be printed when an application runs. Suppose, you are running your application and the program crashes, unfortunately. Then, Logcat Window is going to help you to debug the output by collecting and viewing all the messages that your emulator throws. So, this is a very useful component for the app development because this Logcat dumps a lot of system messages and these messages are actually thrown by the emulator. In Android Studio one of the most used tools is Logcat. Logcat window in Android Studio is used to display real-time system messages and messages that are added in the Log class of the app. To open Logcat Click View > Tool Windows > Logcat (Alt + 6 or from the toolbar window). Sometimes logcat shows nothing and it’s completely blank. This happens often and there can be different reasons. Below are some quick solutions that might work.

Solution 1: Restarting Logcat

You need to press Alt + 6 twice to restart the Logcat. Restarting logcat often helps when it becomes irresponsive. Or you may click on this icon.

Solution 2: Change Log Level

Changing between different log levels like verbose to error or vice versa helps in displaying the logs back.

Solution 3: Plug Unplug

In case you are using the external android device to run the app then you might want to unplug and again plug the device.

Solution 4: Restart Android Studio

By restarting Android Studio, you can resolve this issue.

Solution 5: Select – Show only Selected application

In android studio open the android monitor window from the bottom and from the spinner option menu on the right side select Show only selected application.

Solution 6: Invalidate Caches

Go to the File option > click on “INVALIDATE CACHES/RESTART” then a dialog box will pop up, Select the “INVALIDATE CACHES/RESTART” button. This will automatically restart and build the index of android studio.

Источник

XDA Basics: How to take logs on Android

Logs are very useful when a developer is diagnosing an error with a piece of software. So, as a user, when you complain to a developer about a problem with their Android app or an aftermarket firmware (custom ROM), they’ll ask you to submit a log to help them troubleshoot the issue. Android includes a number of logs that deal with different parts of the firmware, and there are a number of ways to collect those logs. In this guide, we’ll talk about the various common logs and how you can collect them on Android for bug reports.

Читайте также:  Как увеличить громкость блютуз гарнитуры андроид

Before we start, you should set up Android Debug Bridge on your computer as you might need ADB access for some of these logs. We have a great guide on how to set up ADB on any computer.

Kernel panic logs

Kernel panic logs are useful to figure out what happened during an unsuccessful boot. If you’re trying to run a custom ROM but your phone is stuck at the boot loop, you can collect kernel panic logs to help the ROM developer find out what went wrong.

A majority of Android manufacturers use upstream ‘pstore’ and ‘ramoops’ drivers to store kernel logs after a panic. Ramoops writes its logs to the RAM before the system crashes. With root access, these logs can be retrieved from:

The file name could be slightly different but it’ll be in the pstore directory. You can get it using ADB pull or any other way you want. For example:

adb pull /sys/fs/pstore/console-ramoops C:\Users\Gaurav\Desktop\filename

Driver messages

The log from the driver messages buffer can be used to diagnose issues with system drivers and why something isn’t working. On Android, you can use the ‘dmesg’ output to get these logs. You’ll need root access to get these logs though. Use the following ADB command to export the complete log.

System logs

System logs are useful when something in the system throws an error. Android allows collecting system logs using Logcat. Log messages can be viewed in a Logcat window in Android Studio, or you can use the command line tool to pull them.

Several Android apps are also available in the Google Play store that allow easy access to these tools. We’ll talk about these apps later in this article. Moreover, several custom ROMs come with options in the Developers settings to collect the system logs.

To collect logs using ADB, use the following command. This command will export a continuous log, so use Ctrl + C to stop it.

You can use the -d parameter to export the complete log in one go.

If you want, you can also view or save the radio buffer using the following command.

If your device is rooted, you can use the Terminal app on the device itself to collect logs. To save a log using Terminal on your phone, type the following command so the log will be saved on your phone.

Android apps for collecting logs

Logcat Extreme

Logcat Extreme can help you read the logcat and dmesg outputs as well as record logs. It requires root access to show logs properly.

Источник

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