Alternative js log from devices without access to console

Task: Create logging from javascript on device where no access to console

Implementation:

  1. Create doLog.php file on server with:
<?php
if(isset($_GET["q"])){
  $ip = "-";
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  }

  $fp = fopen('log.txt', 'a');
  fwrite($fp, date("Y-m-d H:i:s", time())." [".$ip."] ".$_GET["q"]."\n");
  fclose($fp);
  echo "File appended successfully";
}
else{
  echo "use doLog.php?q=[text]";
}
?>

Use it in your javascript file:


function log(str) {
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "doLog.php?q=" + str);
                xhr.send();
}

log("Log text val="+val);

In this way log will be accessible from web server by [url]/log.txt.

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :