Xamarin for Android: Logging

By September 16, 2013Android, Xamarin
[Please see the Table of Contents for this series.]

In today’s brief posting, I’ll demonstrate how to add logging to your application using the built-in logging facilities provided by the Android.Util namespace.

LoggingTo begin, create a new Android application in Visual Studio  2012 named Hello Log.  When VS settles down, you’ll find a sample file named Activity1.cs that contains almost all the code we need.  This code wires up a button event handler to count the number of times the button is clicked.

Our goal is to add logging to keep track of our place in the program.  To do so, add the line

Log.Info(“JL”, “Start OnCreate”);

Notice that Log.Info takes two arguments, both of type string.  The first is an identifier to make it easier to find your entries in the log.  Here I’ve used my initials.  Feel free to use your own, or if you don’t have initials (that happens to some people) you can use mine.

You’ll also notice that Log.Info has a red squiggly line.  Press control-dot (or whatever shortcut you use) to fix this by adding the necessary using statement,

using Android.Util;

Sprinkle a few more Log.Info statements about, marking the progress of the program, and especially noting the current value of the counter.  For example, I added this line,

Log.Info(“JL”, “Setting up button event handler.

The variable count is ” + count);

That will tell us the value of the counter, but only when the program first runs. To really get interesting information, we need to dive into the event handler.  There are a number of ways to do that; the easiest for such a short event handler, is to use a lambda expression,

button.Click += ((o, e) =>

{

button.Text = string.Format(“{0} clicks!”, count++);

Log.Info(“JL”, “Now the counter is ” + count);

});

Now each time the event handler runs, the Log will be updated. To see the log, click on View->Other Windows->Android Device Logging.  That will bring up a log window, and you’ll easily find your log entries by the tag you created (I’ve surrounded my entries with red boxes to make them especially easy to see):

Android Log

You may also want to experiment with Log.Warn and Log.Error, which produce much more colorful results:

Log.Warn

As you might have expected, the warning is in yellow and the error is in red (well, orange to my eyes).  Notice also that the Log has additional useful information such as

  • The time the entry was logged

  • What type of entry it is (W = warn, E= error, I=Information, V=Verbose)

  • The Process ID

  • The Tag you added

  • The Message you sent in

You can filter by tag, allowing you to zoom in on just your messages.

Filter by tag

I suspect that Logging will come in handy while learning to program the Android using Xamarin.

The following two tabs change content below.