×
Namespaces

Variants
Actions

Simple logging back-end for Nokia Asha Web Apps

From Nokia Developer Wiki
Jump to: navigation, search

This article demonstrates how to use a JavaScript logging framework called Log4js and home brewed PHP back-end to enable simple logging on Series 40 Web apps.

Article Metadata
Compatibility
Platform(s):
Series 40
Article
Created: isalento (12 May 2011)
Last edited: hamishwillee (09 May 2013)

Contents

Introduction

Nokia Asha Web Apps does not currently provide a built in way to log events, hence you have to figure your own ways to do the logging. In this article we are using Log4js, because it is capable of logging events directly to server. Log4js offers AjaxAppender that will use XMLHttpRequest to send events asynchronously to the server.

Phplogger.png

Taking Log4js into use in your Web App

Log4js is easy to add to your project. Just copy log4javascript.js into your project folder and include it in your index.html. Example code is shown below.

Index.html

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>My Web App</title>
<script src="log4javascript.js" type="text/javascript"></script>
<script type="text/javascript" src="basic.js"></script>
</head>
<body>
<!--Content -->
<script type="text/javascript">
var log = log4javascript.getLogger(widget.name);
 
// Set logger to use Server side logger
var ajaxAppender = new log4javascript.AjaxAppender("http://yourdomain.ext/logger/log.php");
log.addAppender(ajaxAppender);
 
log.info("Web App init");
 
//initialize web app
init();</script>
</body>
</html>

PHP Back-end for Log4js

Despite the title this approach could be used for any loggin solution using HTTP POST. Be warned that this implementation is very rudimentary and not suitable to anything else than development purposes. It does not have security procedures at all. Use on your own risk.

The back-end consist of four files.

  • log.php
    • log.php handles the log writing. This is the interface towards Log4js script. It parses the POSTed data and writes log messages into a text file.
  • logreader.php
    • logreader.php monitors changes in a log file and sends updated log file back to the client browser.
  • index.html
    • Client front-end. Shows the log file
  • managelog.php
    • managelog.php handles log file management.

log.php

<?
phpheader('HTTP/1.0 200 Ok');
$logger = $_POST["logger"];
$time = $_POST["timestamp"];
$level = $_POST["level"];
$url = $_POST["url"];
$message = $_POST["message"];
$layout = $_POST["layout"];
$timeString = date("c",$time/1000);
$myFile = 'log.txt';
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh,$timeString ." ".$logger." ".$level." ".$message."<br>\n");
fclose($fh);
?>

logreader.php

<?php
 
header('HTTP/1.0 200 Ok');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); //
 
$filename = 'log.txt';
 
$lastupdate = isset($_GET['lastupdate']) ? $_GET['lastupdate'] : 0;
$filemodified = filemtime($filename);
 
$start = time();
$keepalive = false;
 
while ($filemodified <= $lastupdate) // check if new entries have been inserted
{
usleep(20000); // 20ms sleep
clearstatcache(); //clear cached info about file
$filemodified = filemtime($filename);
 
if(time() - $start > 10){
$keepalive = true;
break;
}
}
 
// return a json array
$response = array();
 
if($keepalive){
$response['log'] = "";
$response['timestamp'] = $lastupdate;
}else{
$response['log'] = file_get_contents($filename);
$response['timestamp'] = $filemodified;
}
 
echo json_encode($response);
flush();
 
?>

managelog.php

<?php
 
header('HTTP/1.0 200 Ok');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); //
 
$filename = 'log.txt';
 
$action = isset($_GET['action']) ? $_GET['action'] : "";
 
if($action == "clear"){
 
$timeString = date("c");
 
$myFile = 'log.txt';
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,"Cleared at ".$timeString."<br>\n");
fclose($fh);
}
 
?>

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Logger for Web Apps</title>
<script type="text/javascript">
 
var logginEnabled = false;
var request = null;
var serverurl = "./readlog.php";
var lastupdate =0;
function checklog(){
 
try {
if (!request) {
request = new XMLHttpRequest();
}
else
if (request.readyState != 0) {
request.abort();
}
 
request.onreadystatechange = handleResponse;
var url = serverurl+"?lastupdate="+lastupdate;
console.log(url);
request.open("GET", url, true);
request.send(null);
}
catch (e) {
alert("request sending error " + e);
}
}
 
function handleResponse(){
 
if (request.readyState == 4) {
if (request.status == 200) {
 
var resp = eval('(' + request.responseText + ')');
lastupdate = resp["timestamp"];
console.log(lastupdate);
 
//keepalive results in a empty string
if(resp.log != "")
updateLog(resp.log);
else
console.log("keepalive");
 
if(logginEnabled)
setTimeout(function(){checklog(); }, 500);
}
else {
if(request.status != 0) //req aborted
alert("Log retrieval error: " + request.status + " " + request.statusText);
}
 
}
}
 
function toggleLogging(){
 
if(!logginEnabled){
logginEnabled = true;
checklog();
document.getElementById("logButton").value = "Stop";
 
}else{
logginEnabled = false;
request.abort();
document.getElementById("logButton").value = "Start";
}
 
}
 
function clearlog(){
try {
var clearReq = new XMLHttpRequest();
 
clearReq.onreadystatechange = function(){
if (clearReq.readyState == 4 && clearReq.status == 200) {
alert("cleared");
}
}
clearReq.open("GET", "./managelog.php?action=clear", true);
clearReq.send(null);
 
}catch (e) {
alert("Clear failed " + e);
}
}
 
function updateLog(text){
document.getElementById("log").innerHTML = text;
}
</script>
</head>
<body>
<input type="button" id="logButton" onclick="toggleLogging();" value="Start"/>
<input type="button" onclick="clearlog();" value="Clear Log"/>
<div id="log"></div>
 
</body>
</html>
This page was last modified on 9 May 2013, at 13:37.
64 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×