Log in android application

Android Essentials: Application Logging

In this quick tip tutorial, you’ll learn how to use application logging support in your Android applications for diagnostic purposes.

This quick tip shows you the steps to incorporate logging support into your applications and then use the LogCat logging utility to monitor your application’s log output, either on the emulator or a device that is attached to Eclipse via the debugger. This skill is invaluable for debugging issues, even when great debuggers are available for stepping through code.

Step 1: Create an Android Application

Begin by creating an Android project. Implement your Android application as normal. Once you’ve setup your Android project, you are ready to proceed with this quick tip.

Step 2: Logging Options for Android Applications

The Android SDK includes a useful logging utility class called android.util.Log. Logging messages are categorized by severity (and verbosity), with errors being the most severe, then warnings, informational messages, debug messages and verbose messages being the least severe. Each type of logging message has its own method. Simply call the method and a log message is created. The message types, and their related method calls are:

  • The Log.e() method is used to log errors.
  • The Log.w() method is used to log warnings.
  • The Log.i() method is used to log informational messages.
  • The Log.d() method is used to log debug messages.
  • The Log.v() method is used to log verbose messages.
  • The Log.wtf() method is used to log terrible failures that should never happen. («WTF» stands for «What a Terrible Failure!» of course.)

The first parameter of each Log method is a string called a tag. It’s common practice to define a global static string to represent the overall application or the specific activity within the application such that log filters can be created to limit the log output to specific data. For example, you could define a string called TAG, as follows:

You will often find that the tag is defined as the class in which the Log statement occurs. This is a reasonable convention, but anything identifiable or useful to you will do.

Now anytime you use a Log method, you supply this tag. An informational logging message might look like this:

You can also pass a Throwable object, usually on Exception, that will allow the Log to print a stack trace or other useful information.

NOTE: Calling the Log.wtf() method will always print a stack trace and may cause the process to end with an error message. It is really intended only for extreme errors. For standard logging of exceptions, we recommend using the Log.e() method. The Log.wtf() method is available only in Android 2.2 or later. The rest are available in all versions of Android.

Step 3: Adding Log Support to an Activity Class

Now let’s add some logging to your Activity class. First, add the appropriate import statement for the logging class android.util.Log. Next, declare a logging tag for use within your class (or whole application); in this case, we call this variable DEBUG_TAG. Finally, add logging method calls wherever you want logging output. For example, you might add an informational log message within the onCreate() method of your Activity class.

Below is some sample code that illustrates how all these steps come together:

Step 4: Monitoring Application Log Output – The Easy Way

You can use the LogCat utility from within Eclipse to view the log output from an emulator or device. LogCat is integrated into Eclipse using the Android Development plug-in. You’ll find the LogCat panel integrated into the DDMS and Debug perspectives of Eclipse.

Step 5:Monitoring Application Log Output – Creating Log Filters

As you can see, the basic LogCat logging output includes log data from lots of different sources. For debugging purposes, it can be useful to filter the output to only the tags for your specific application. This way, you can focus on your application log output, amidst all the clutter.

Читайте также:  Как android для nokia 5230

You can use the LogCat utility from within Eclipse to filter your log messages to the tag string you supplied for your application. To add a new filter, click the green plus sign button in the LogCat pane of Eclipse. Name the filter—perhaps using the tag name—and fill in the tag you want to filter on. A new tab is created in LogCat that will show only log messages that contain this tag. You can create filters that display items by severity level.

Performance Considerations with Logging

Logging output puts a damper on application performance. Excessive use can result in decreased application performance. At minimum, debug and verbose logging should be used only for development purposes and removed before release. It’s also a good idea to review other logging output before publication as well.

Conclusion

Logging is a very handy debugging and diagnostic technique used by developers. Use the logging class provided as part of the Android SDK to log important information about your application to LogCat, but make sure you review your application’s logging implementation prior to publication, as logging has performance drawbacks.

Источник

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.

Источник

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

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

Читайте также:  Диагностика рено елм 327 смартфоном андроид

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

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

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

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

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

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

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

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

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

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

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

Источник

Keep the user logged in android app.

Jul 5, 2017 · 4 min read

Hello everyone, in this lesson, we will see how to keep the user logged in android apps.
We have seen in almost every app that the user logs in for the first time and the next time he opens the app, he goes straight inside the app without authentication.
Let’s try doing it in a simple way. We will build an app for that. The app will contain two screens

  • Login screen : This will have a button. Once we click the button we will go to MainActivity.
  • MainActivity : The screen that user will come on after login.

So we will be trying to write t he code so that the user clicks on the button and goes to the MainActivity for the first time, and from the next time onwards, he directly goes to MainActivity when he opens the app.

Let’s write the code for LoginActivity. The button and the intent on the click event of button. Simple.

In the java file, lets take reference and click event on the button.

now let’s write a method to move to the MainActivity. This function will contain only the Intent, nothing complex.

Now let’s call this function on the button click

So the LoginActivity.java looks like this

Now we will be applying the logic to remain logged in, So the summary of the steps up to now

  • A button and it’s initialization
  • A function goToMainActivity() having the intent.
  • Calling the function on button click. So when the user clicks the button, intent is called and he goes to MainActivity.

SharedPreferences Overview

SharedPreferences in android store values in key-value fashion.
We initialize the SharedPreferenes with a particular name, which will be constant for the whole app. It is done as following.

so we will be initializing in our app with name “login” and mode “private”. it looks like

For storing values in SharedPreferences, we use edit() and then put the keys and values of corresponding data type.

So here in first one, we are saving a String value. We have our own key name and we are putting the value Bruce Wayne .

In second one, we are saving an Integer value. Our key is age and the value is 30 .

In third, we are saving a Boolean value. Our key is isSuperHero and the value is true .

As we can see that we are defining our keys ourselves. So we know which key stores which value. So while retrieving the values, we use this key and the default value.

this will give the value for that particular key.
Let’s try getting the three values back which we saved above.

Now that we know how to use SharedPrefernces, let’s try using it in our application.

Читайте также:  Что такое csc андроид

Applying SharedPreferences logic in our app

Editing the LoginActivity, let’s add and initialize the SharedPreferences.

now sp is ready to store values.
To check if the user is logged in once into the app, let’s save a boolean value isLogged into sp after login is completed.

and every time the activity starts, check for the value. If we get true, it means login is completed, because only after login, we are making it true. If we get false, it means login is not done, because the default value of Boolean is false.
So if we know that user has logged in already, we will send him to MainActivity directly and login screen will skip.

Источник

Keep the user logged in android app.

Jul 5, 2017 · 4 min read

Hello everyone, in this lesson, we will see how to keep the user logged in android apps.
We have seen in almost every app that the user logs in for the first time and the next time he opens the app, he goes straight inside the app without authentication.
Let’s try doing it in a simple way. We will build an app for that. The app will contain two screens

  • Login screen : This will have a button. Once we click the button we will go to MainActivity.
  • MainActivity : The screen that user will come on after login.

So we will be trying to write t he code so that the user clicks on the button and goes to the MainActivity for the first time, and from the next time onwards, he directly goes to MainActivity when he opens the app.

Let’s write the code for LoginActivity. The button and the intent on the click event of button. Simple.

In the java file, lets take reference and click event on the button.

now let’s write a method to move to the MainActivity. This function will contain only the Intent, nothing complex.

Now let’s call this function on the button click

So the LoginActivity.java looks like this

Now we will be applying the logic to remain logged in, So the summary of the steps up to now

  • A button and it’s initialization
  • A function goToMainActivity() having the intent.
  • Calling the function on button click. So when the user clicks the button, intent is called and he goes to MainActivity.

SharedPreferences Overview

SharedPreferences in android store values in key-value fashion.
We initialize the SharedPreferenes with a particular name, which will be constant for the whole app. It is done as following.

so we will be initializing in our app with name “login” and mode “private”. it looks like

For storing values in SharedPreferences, we use edit() and then put the keys and values of corresponding data type.

So here in first one, we are saving a String value. We have our own key name and we are putting the value Bruce Wayne .

In second one, we are saving an Integer value. Our key is age and the value is 30 .

In third, we are saving a Boolean value. Our key is isSuperHero and the value is true .

As we can see that we are defining our keys ourselves. So we know which key stores which value. So while retrieving the values, we use this key and the default value.

this will give the value for that particular key.
Let’s try getting the three values back which we saved above.

Now that we know how to use SharedPrefernces, let’s try using it in our application.

Applying SharedPreferences logic in our app

Editing the LoginActivity, let’s add and initialize the SharedPreferences.

now sp is ready to store values.
To check if the user is logged in once into the app, let’s save a boolean value isLogged into sp after login is completed.

and every time the activity starts, check for the value. If we get true, it means login is completed, because only after login, we are making it true. If we get false, it means login is not done, because the default value of Boolean is false.
So if we know that user has logged in already, we will send him to MainActivity directly and login screen will skip.

Источник

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