Logging system in android

Android: логгирование и отправка результатов на почту

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

Одно дело — разработка, LogCat в Android Studio (если вы из любителей пожестче — можно распечатку в консоли смотреть с помощью adb), и совсем другое — ломать голову над вопросом почему у вас все работает на всем парке тестовых устройств, а пользователь жалуется на абсолютно обратную ситуацию. Коммуникация между разработчиком и конечным пользователем — это хорошо, но совсем другое — видеть своими глазами картинку происходящего (помните, как в матрице — для кого-то это зеленые иероглифы, а для кого-то — женщина в красном?)

Предлагаю разбить задачу на несколько частей, а именно — сбор и хранение логов, способ их передачи из одного приложения в другие с помощью FileProvider, ну и небольшой helper класс для создания писем с аттачами. Итак, поехали.

Сбор и хранение логов.

Кто-то использует System.out.println, кто-то — статические методы класса Log. Я с некоторых пор пришел к написанию своего класса для распечатки логов. Давайте вкратце расскажу почему.

Во-первых, это проще. Как правило, для отслеживания изменений в процессе выполнения приложения я использую одну и ту же метку. И вот однажды я подумал — зачем ты пишешь постоянно Log.i(MY_TAG, «info») если можно сократить немного и убрать из этой формулы одну постоянную?

Во-вторых, расширение логгирования. Это конкретно упирается в нашу задачу — хранение логов в файлах. Можно написать отдельный класс, в который будем передавать какие-то данные, как то: данные и имя файла, но данные мы уже передаем в метод Log.i / Log.e / проч., создавать лишний раз переменную что ли для этого? Некрасиво все это как-то.

Ладно, довольно лирики, давайте лучше взглянем на класс Diagnostics.

Для того, чтобы вывести информацию в LogCat с дефолтной меткой, достаточно написать следующее:

Иногда мне хочется видеть какие методы вызываются и в каких объектах. И с какими параметрами или значениями переменных. В общем, тут важно для меня — где именно производится вызов. Тогда я использую следующую конструкцию

Diagnostics.i(this, “onCreate w/param1 = “ + param1);

где this — это экземпляр класса Caller. Например, для MainActivity вы увидите следующее:

03–29 12:31:53.203 16072–16072/com.isidroid.platform I/Diagnostics: MainActivity.onCreate w/param1 = 200

И все сразу становится понятно — кто вызывает и где вызывает.

А теперь о хранении этой информации.

Как вы уже могли видеть, в классе Diagnostics есть методы для работы с файлами — createLog и appendLog. Объяснять, я думаю, не стоит — первый создает файл, второй — добавляет в него строку. Для новичков или тех, кто ленится читать код, уточню — appendLog создает файл, если его не существует, а createLog всегда создает новый. Чтобы лишней информации там не хранилось.

Файлы хранятся в cache директории, которая, к слову, недоступна для других приложений (ну, если у вас телефон не рутован, конечно).

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

Надеюсь, это выглядит просто в использовании.

Передача файлов в другие приложения

Как я уже говорил выше, наши файлы для лога хранятся в некоторой защищенной от чужих глаз папке. Она настолько защищена, что если вы попробуете передать файлы в другое приложение с использованием относительного пути File.getAbsolutePath(), то вы потерпите неудачу.

На помощь к нам мчится FileProvider, друзья!

Вообще, в документации есть отличная статья (она же — пошаговая инструкция) на эту тему — Setting Up File Sharing, но для тех, кто предпочитает читать StackOverFlow и isidroid.com, я приведу выжимку из статьи с кодом реализации.

  1. Добавляем FileProvider в Manifest.

2. Указываем директории, доступные для шаринга. Для этого создаем файл res/xml/cache_file_paths и для нашего конкретного примера заполняем его.
Конец.

Нет, правда, это все.

На самом деле это довольно мощный инструмент для работы с файлами в вашем приложении, но в рамках поставленной задачи это все, что нам нужно сделать. Подробности — в официальной документации.

Читайте также:  Китайские телефоны с русским андроидом

Отправка писем с логами.

Мы с вами почти добрались до конца, осталось дело за малым. Вообще, создание намерения (intent) для отправки писем — это довольно тривиальная задача, чтобы под нее писать отдельный хелпер. Но с другой стороны, если можно причесать код в вашей Activity / Fragment, то почему бы и нет, верно?

Гораздо симпатичнее будет выглядеть какой-нибудь строитель (builder) в коде нежели условия, проверки и лишние циклы. Я за то, чтоб это выносить в отдельный класс (кстати, не только я ратую за разделение представления от бизнес-логики).

Давайте перейдем сразу к сути. Сначала я покажу класс (который вы можете скопировать и использовать не глядя, конечно), а потом пример его использования. Поехали!

Где this — это Activity.

Вы можете самостоятельно указать «рыбу» для текста письма, но я рекомендую использовать те данные, которые указаны в методе buildContent, расширяя их при необходимости. Можно конечно извернуться и применить паттерн «декоратор» для расширения этих данных без модификации класса FeedbackHelper, но лично для меня необходимости в этом не было… Что до вас, то дерзайте!

Источник

Логирование в Android приложениях

Уверен, что всем разработчикам приложений на платформе Android знаком класс Log, позволяющий логировать различные события. По различным причинам, формат записи логов для каждого проекта может отличаться достаточно сильно — начиная от «AAA», «111111» и «I was here» до более-менее внятных — «Opening HTTP connection to habrahabr.ru». Под катом вы найдете пример функции, которая поможет навести порядок в логах.
Данный топик не претендует на оригинальность и универсальность. И поэтому, если в вашем проекте уже существует некий стандарт логирования событий, то смело проходите мимо — топик скорее ориентирован на начинающих разработчиков.

Как правило, ценность логов начинаешь понимать только когда заказчик матерясь отсылает лог на почту и просит засабмитить фикс через 5 минут. И если лог состоит из сообщений невнятного характера, то как минимум, разбр данного лога займет куда больше времени, чем хотелось бы.

Пытаемся навести порядок

Логи существуют для того, чтобы разработчик мог понять что, где и когда произошло. Найти ответ на вопрос «когда произошло» достаточно просто — в логах Андройд записывает время события. Нахождение ответа на вопрос «что произошло» так же не вызывает больших трудностей, если сообщение в лог было написано со смыслом, например: «Opening file. ». Вопрос «где произошло» оказывается наиболее сложным. Если проект большой, то придеться потратить время на нахождение нужного места кода, даже, если лог был написан со смыслом.

Если событие логируется с указанием Throwable (чаще Exception), например, метод public static int d (String tag, String msg, Throwable tr) , то в консоле сообщений будет выведен стек, который поможет быстро идентифицировать место логирования. Но использование данного метода без особой необходимости до безобразия перегрузит лог ненужной информацией.

Если же логируется просто текст, то при логировании можно явно указывать место вызова. Например:

Однако, писать такое каждый раз — дело утомительное и неблагодарное.

Ниже приведен пример класса Log , который делает это автоматически.

Использование класса очень простое:

Результатом логирования данным способом будут примерно следующие строки:

Примечание:
По понятным причинам, данный способ мало пригоден для приложений «пропущенных» через обфускатор.

В общем-то все.
Прошу прощения, если эта статья показалась слишком тривиальной для хабра.

Источник

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.

Источник

Debugging and Logging Android App

Introduction

In this post, I will tell you all android logging library and debugging tool. Logging android app helps you to debug a bug and exception in local or remote. It can be production and development environment. Few things you can logging android studio

Requirements

In development mode, you are always faced errors, exceptions, and crashes. It can be tracked by android logging system or Logcat. When it’s come in production app, it not easy to debug because in the users’ device can be so many reasons for any mishappening, such as low network connectivity, device configuration, memory, CPU uses etc. I will tell you all android logging library and debugging tool that help you to find out real problem local and remote as well

Crashes and exceptions can be logged local and remote server as well. Debugging & Logging android app is compulsory to build a pro android application.

Major problem in android app development

  • You can not check & view shared preference variables – View the shared preference and local database is not easy in android studio.
  • For logging (standard logging) always need to give tags. Basically, In a big team follow the same logging standard by all developers is not easy. I will discuss some libraries that provide a centralized logging system in all app.
  • Remotely view logs for all devices – We can debug and log locally, mean those are connected in Android Studio via USB debugging. Android logging system does not provide remote logging solution.
  • Database access is very difficult – Check the database data little bit tricky in android app development
  • Inspect elements – Inspect all element and network call is not easy and trackable

Following most debugging tools and libraries for logging android app

  1. Bugfender
  2. Android Debug Database
  3. Fabric Crashlytics (Firebase) & Answer
  4. Stetho
  5. Timber

1. Bugfender

The remote logging system for iOS and Android application. Bugfender is a best for remote logging android app. You can log each event with a custom parameter in an orgenized way. You can easily debug what went wrong of user device using logging android

Читайте также:  Как прошить планшет андроид через компьютер если планшет не включается

Why Bugfender? At the time of development

  • Logs from many devices required.
  • Not possible to attach all the devices with the development machine.
  • Need to check some special values on some events fire.
  • The log will be saved on cloud and log file can be downloaded as well.
Features
  • Logged all remote devices logs.
  • You can setup cloud-based logging.
  • Bugfender provides free version provides last 24 hours logs.
  • Shows different logs for different devices.
  • One can enable/disable devices as well as logging on those devices.
  • Have different methods to print UI logs, all events logs(complete Android system logs).
  • The developer can log only particular event logs.

2. Fabric Crashlytics (Firebase)

For all types crash ‘Fabric’s Crashlytics’ provide a solution for that. Fabric’s SDK logged all crashes and exceptions remotely with user device configuration

Benefits:
  • Able to log errors and exception an complete stack trace for remote devices
  • Gives log for debug as well as for production environment.
  • It provides all details of device models.
  • All the crashes and exceptions will be notified via email, every time they occur.
  • Crashes reported automatically.
  • To log caught exceptions crashlytics.logException(exception);
  • We provide some key-value pair for more reference of exception.
Limitations
  • Sometimes didn’t get complete context of a class where an error occurs.
  • Android logs for crashes are sometimes difficult to understand.

3. Stetho

Stetho is mainly a debugging and logging library for Android apps. It developed by Facebook. It uses Chrome’s Developer tool to display debugging data of apps. You can debug all things in local using logging android app.

Features provided:
  • View Hierarchy
  • Database inspection
  • Shared Preferences
  • JavaScript Console
  • Dumpapp

2.1 View Hierarchy: Able to view all the View elements and detailed properties (styles). The user will have a complete hierarchy view of layout including layouts which were integrated at runtime.

2.2 DataBase Inspection: User views complete database tables and also able to do the query for some specific data and also alter the data directly from here.

2.3 Shared Preferences: User can view all the shared preferences variables and also changes these values.

2.4 Network Inspection: User can view all the network request and JSON response, image preview of application.

2.5 JavaScript Console: User can interact with the application and even Android SDK by executing javascript code in the console.

2.6 Dumpapp: Provided command line interface for the Android application.

Integration: Follow the below link

User runs the code, He will see request and response in the ‘Network’ tab of Developers tool.

Inspection Process- You have done with all integration steps than move to chrome browser

  • Open chrome browser in the developer system.
  • Navigate to ‘chrome://inspect’.
  • Here user will find all the connected devices with the Application name.
  • Click ‘inspect’ to start the inspection.

4. Timber’s Requirement:

Timber is a logging library that manage all log in organised way logging android studio.

  • Do not require to specify ‘TAG’ for class context like ‘Android log system. Its timber’s inbuilt feature.
  • Can control which kind of logs want to show in crashlytics. eg. errors and exceptions. It will not show ‘info’ and ‘warnings’ log in crashlytics.
  • We can print line-number as well with the logs.
  • Provide all logging methods, provided by ‘Android logging system’. Like, debug, info, error, wtf etc

Integration:

  • Follow the timber integration instruction
  • Add the following in-app level Gradle file
  • In Application, class add below code

Now timber provides all kind of logging eg. debug, info, verbose etc in ‘Developer tool’s console’. Do not need to add ‘TAG’, just add messages where ever it is required.

Limitations
  • Do not work for remote devices.
  • Logging can’t be saved.

5. Android Debug Database

This android logging library allows you to view databases & shared preferences in your development machine browser.

Features
  • View database.
  • Run sql query to modify or delete data from DB.
  • View/edit/delete shared preferences of application.
  • Directly edit the database values.
  • Search and sort data.
  • Download database.
Limitations
  • Development machine & device should be in the same network.

Integration: Follow the link

Источник

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