<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Remote Logging on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/remote-logging/</link>
    <description>Recent content in Remote Logging on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 12 Dec 2011 19:53:04 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/remote-logging/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Log to a file on computer in Android</title>
      <link>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</link>
      <pubDate>Mon, 12 Dec 2011 19:53:04 +0000</pubDate>
      <guid>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</guid>
      <description>&lt;p&gt;It’s been a long time since the last time I blogged about something, and many things have changed since then,&lt;/p&gt;
&lt;p&gt;I graduated, got engaged and moved to Dubai.&lt;/p&gt;
&lt;p&gt;I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png&#34; rel=&#34;lightbox[310]&#34; title=&#34;Androids&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png&#34; alt=&#34;&#34; title=&#34;Androids&#34; width=&#34;300&#34; height=&#34;105&#34; class=&#34;aligncenter size-medium wp-image-315&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;Now let’s move to business, so I was working on an &lt;a href=&#34;http://developer.android.com/index.html&#34; title=&#34;Android Developers&#34;&gt;Android&lt;/a&gt; application and I needed to log some debug messages, normally I’d use &lt;code&gt;Log.d(TAG, message);&lt;/code&gt; and this will send the message to &lt;a href=&#34;http://developer.android.com/guide/developing/tools/logcat.html&#34; title=&#34;logcat | Android Developers&#34;&gt;logcat&lt;/a&gt;, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>It’s been a long time since the last time I blogged about something, and many things have changed since then,</p>
<p>I graduated, got engaged and moved to Dubai.</p>
<p>I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[310]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a>Now let’s move to business, so I was working on an <a href="http://developer.android.com/index.html" title="Android Developers">Android</a> application and I needed to log some debug messages, normally I’d use <code>Log.d(TAG, message);</code> and this will send the message to <a href="http://developer.android.com/guide/developing/tools/logcat.html" title="logcat | Android Developers">logcat</a>, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.</p>
<p>So usually in such situations we use files and log whatever we need inside them, but I’m working on an Android phone/emulator, and dealing with files and logging to them and reading them later from the computer will be a tedious thing to do, so I came up with a simple solution to log messages from Android to my computer.</p>
<p>The idea is to create a simple web server that accepts POST requests, these requests have only one parameter which is the data to be logged. I made it as simple as possible, I could have defined levels for logging and tags and other sorts of things, but I wanted a simple solution that wouldn’t take more than five minutes to write and get it working.</p>
<h3 id="simple-web-server">Simple web server</h3>
<p>Since I’m a pythonist geek I couldn’t think of anything better than Python to implement the simple web server, and it was really great, since I didn’t have to write so much code!</p>
<p>I’ll be using <code>HTTPServer</code> and <code>BaseHTTPRequestHandler</code> from <a href="http://docs.python.org/library/basehttpserver.html">BaseHTTPServer</a> module, some <a href="http://docs.python.org/library/threading.html">threading</a> and <a href="http://docs.python.org/library/cgi.html">cgi</a>.</p>
<pre class="lang:python decode:true">from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import threading
import cgi
import time

IP = '192.168.1.3'
PORT = 5500

LOG_FILE = r'C:\AndroidLogFile.log'

POST_PARAMETER = 'log'
</pre>
<p>I set the server to run on port 5500, don’t ask why I chose this number, I didn’t think of it 😛</p>
<p>I define a function that will execute a function in a separate thread as a daemon thread:</p>
<pre class="lang:python decode:true">def startThread(fn):
    thread = threading.Thread(target=fn)
    thread.setDaemon(True)
    thread.start()
    return thread
</pre>
<p>I define the block of code to be executed when running the server:</p>
<pre class="lang:python decode:true">if __name__ == '__main__':
    httpd = HTTPServer((IP, PORT), lambda *args, **kwargs: LogHandler(*args, **kwargs))
    serve_thread  = startThread(httpd.serve_forever)
    while serve_thread.isAlive():
        serve_thread.join(timeout=1)
</pre>
<p>Here I created an HTTP web server that is bound to the IP/PORT set at the beginning of the script, and I mapped the handler for this web server to a class called LogHandler.</p>
<p>This handler will handle the requests, and hence it’ll handle POST requests and save their contents into the specified file.</p>
<pre class="lang:python decode:true">class LogHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def do_POST(self):
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        f = open(LOG_FILE, 'a')
        f.write('%s:\n%s\n%s\n' % (time.strftime('%Y/%m/%d %H:%M:%S'), postvars[POST_PARAMETER][0], '*' * 20))
        f.close()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Cache-Control', 'no-cache')
        self.end_headers()
        self.wfile.write('Saved!')
</pre>
<p>Pretty simple, not more than 35 lines of code!</p>
<p>Now let’s move to the Android/Java side.</p>
<h3 id="androidjava-class">Android/Java class</h3>
<p>This class will be responsible for sending POST requests to the server, I’ll be using Apache classes to do the HTTP requests, and I’ll use some other classes from Java standard library, along with Android log class to log exceptions.</p>
<pre class="lang:java decode:true">import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
</pre>
<p>The class starts with defining some constants:</p>
<pre class="lang:java decode:true">public class LogToFile {
	private static final String LOG_TO_FILE_ADDRESS = "http://192.168.1.3";
	private static final String LOG_TO_FILE_URL = "/";
	private static final String LOG_TO_FILE_LOG_PARAMETER = "log";
	private static final int LOG_TO_FILE_PORT = 5500;
</pre>
<p>Then I define a method that constructs an HTTP POST request to the specified url along with the specified parameters:</p>
<pre class="lang:java decode:true">private static HttpPost Post(String url, HashMap&lt;String, String> params, HashMap&lt;String, ArrayList&lt;String>> arrayParams) {
		try {
			if (!url.endsWith("/"))
				url += "/";
			List&lt;NameValuePair> params_list = null;
			if (params != null) {
				params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, String> entry : params.entrySet())
					params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			if (arrayParams != null) {
				if (params_list == null)
					params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, ArrayList&lt;String>> entry : arrayParams.entrySet())
					for (String value : entry.getValue())
						params_list.add(new BasicNameValuePair(entry.getKey(), value));
			}
			HttpPost request = new HttpPost(url);
			if (params != null)
				request.setEntity(new UrlEncodedFormEntity(params_list, "utf-8"));
			return request;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>I know this is a lot of code for such thing, but this method is used elsewhere in my application and that’s why it had to be this generic.</p>
<p>Another method will be used to execute the request, also it is generic to be used elsewhere, you can edit the code and make it more specific to your needs.</p>
<pre class="lang:java decode:true">private static HttpResponse ExecuteRequest(HttpUriRequest request) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(request);
			return response;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>And now to the final piece of code here, this is the method that you’ll call from anywhere in your application to log messages to the file:</p>
<pre class="lang:java decode:true">public static void LogToFile(String log) {
		try {
			HashMap&lt;String, String> params = new HashMap&lt;String, String>();
			params.put(LOG_TO_FILE_LOG_PARAMETER, log);
			HttpPost request = Post(String.format("%s:%d%s", LOG_TO_FILE_ADDRESS, LOG_TO_FILE_PORT, LOG_TO_FILE_URL), params, null);
			HttpResponse response = ExecuteRequest(request);
			response.getEntity().consumeContent();
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file">Project on GitHub</a></p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
  </channel>
</rss>
