JavaScript Log Tool

Source: Internet
Author: User
Tags date array current time join key log return log4j
Javascript

A few days ago, learning Ajax, the feeling of the control of JavaScript some trouble, especially often use alert () statement to output some records, it is very inconvenient. Then went to the Internet to search some JavaScript logging tools, feel that there are some small shortcomings, not suitable for themselves. So, I simply also wrote a logging tool, used to feel good. Here is the introduction to everyone to see.

This tool is just a JS script file. Easy to use, just put this script file and HTML file in the same directory, and then use the <Head> and </Head> in the middle of the following statement can be added:
<script src= "Mxjlogger.js" type= "Text/javascript" ></script>

This is a simple JavaScript logger tool, similar to the Java log4j. Divided into 5 levels, from low to High is: Debug info warn error fatal. The default is to display and at the debug level record activation state. The shortcut key is Alt + D, and you can pull or hide the tool. When scrolling, it does not scroll with the scroll bar.

Once this JS script is introduced, a total of 5 methods can be invoked in JavaScript, which is debug () info () warn () error () Fatal ().

Called in <script></script>, as follows: part of the statement
<script src= "Mxjlogger.js" type= "Text/javascript" ></script>

<script type= "Text/javascript" >
Debug ("Welcome to use JAVAMXJ developed JavaScript Logger");
Debug ("My blog:http://blog.csdn.net/javamxj/")
Info ("Current time is:" + new Date ());
</script>


You can also call it directly in the method, as follows: Partial statements
<button style= "Color:green" >
Send Debug Information
</button>




The complete test file testlogger.html and script file Mxjlogger.js are as follows:
Testlogger.html
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >



Mxjlogger.js
/*  This is a simple JavaScript logger tool, similar to the Java log4j.   divided into 5 levels, from low to High is: Debug info warn error fatal   default is to display and at the debug level Record activation state   shortcut key is Alt + D, pull up this tool   author: j avamxj  Date: August 8, 2006   version:1.0    my blog:http://blog.csdn.net/javamxj/ . My Email:javamxj@gmail.com*/var _logger = true;              /Whether to activate the output var log_area;                    //Record area var n=0;//------------------------------//Level setting and its corresponding output color//----------- -------------------var levelarray = ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"];    var colorarray = [" Green "," Blue "," Red "," Black "," #800000 "];var arr = new Array (); for (var i=0; i<levelarray.length; i++) {Arr[i] =" <op Tion> "+ levelarray[i] +" </OPTION> ";} ------------------------------//write out the relevant HTML statements//------------------------------document with document.write. Write (' <div ID = "Javamxj_log" style= "position:fixed!important;position:absolute; top:310px;width:90% : 2000;display:block;border-style:groove;border-width:thin; " > ' +               ' <div style= ' Background-color: #EFE8E0 "> ' +                 ' <input type = ' button ' name = ' Clear ' value = ' purge '   onclick = ' $ (\ ' Status_area\ '). innerhtml=\ ' \ '/& gt;     ' +                ' <input type = ' button ' id= ' javamxj_run ' name = ' javamxj_run ' value = ' Stop | Hidden record '   onclick = ' togglelog () '/& gt;         ' +                ' Level: <select id= "Levelselect" > "+ arr.join () +" </select></div> "+& Nbsp;               ' <div id = ' Status_area ' name = ' Status_area ' style= ' height:250px;overflow:auto;opacity:0.8; Filter:alpha (opacity=80); " ></div> ' +               ' </ Div> '),//------------------------------//fixed in original position//when scrolling------------------------------document.body.onscroll= function () {   javamxj_log.style.postop=document.body.scrolltop+document.body.clientheight-280}//----- -------------------------//Increase the speed of "alt+d"//------------------------------Document.onkeydown = function () {              var accesselement = document.createelement (' Span ')     accesselement.innerhtml = ' <button style= ' position:absolute;top:-100px ' accesskey= ' d ' ></button> '     document.body.appendChild (accesselement);} ------------------------------//Learn from Protype, will document.getelementbyiD () packaged into $ () for easy use//------------------------------function $ () {   var elements=new Array ();      for (var i=0;i<arguments.length;i++) {        var element= arguments[i];           if (typeof element== ' string ')      Element=document.getelementbyid (Element);            if (arguments.length==1)     return element;            Elements.push (Element);      }  return elements; }//-------- ----------------------//Get current time//------------------------------function GetCurrentTime () {    var Now=new Date ();   var hours=now.gethours ();   var minutes=now.getminutes ();   var Seconds=now.getseconds ()   var timevalue= "" + ((hours>12)? hours-12:hours);   if (timevalue== "0") timevalue=12;   timevalue+= (minutes<10) ": 0": ":") +minutes;   timevalue+= ((seconds<10)? ": 0" : ":") +seconds;   timevalue+= (hours>=12)? (PM) ":" (a.m.) ";     return timevalue;  } //------------------------------// Wrap 5 different levels of output//------------------------------function debug (message) {logger (0);} Function Info   {Logger (message, 1);} function warn (message)   {logger (message, 2);} Function error (message) {Logger (message, 3);} function fatal (message) {Logger (message, 4);} ------------------------------//output record//------------------------------function Logger (message,num_level) {  var color;  var level;          if (_logger) {           color = colorarray[num_level];    level = Levelarray[num_level];     display = (num_level >= $ ("Levelselect"). SelectedIndex) ? "Block": "None";            if (display = = "block") {       n=n+1;             }     Bg_color = ((n% 2) ==0)? "#FFF": "#F6F6F6";      $ ("Status_area"). InnerHTML = ' <div id= ' + num_level + ' style= ' backg Round-color: ' + bg_color + ';d isplay: ' + display +  ' ><strong style= ' color: ' + color + ' > ' + level + ': ' + ' </strong> ' + getcurrenttime ()    + ":" + message + ' </div> ' + $ ("Status_area") .innerhtml;  }   }//------------------------------//change record level//------------------------------function Changelevel () {  selectedlevel = $ (' levelselect ') .selectedindex;    var m=0;  var divs = $ (" Status_area "). getElementsByTagName (" div ");  for (i=0;i<divs.length;i++) {                 Divs[i].style.display = (divs[i].id >= selectedlevel)? ' Block ': ' None ';            if (divs[i].style.display = = " Block ") {        m=m+1;               Divs[i].style.backgroundcolor = ((M% 2) ==0)? "#FFF": "#F6F6F6";     }       }}//---------------- --------------//Change record status//------------------------------function Togglelog () {  var disp=$ (' Status_area '). style.display;  if (disp = = ' None ') {    $ (' Status_area '). style.display = ' block ';   & nbsp $ (' Javamxj_run '). Value = ' Stop | Hide record ';    _logger = true; } else {    $ (' Status_area '). style.display = ' None ';     $ (' Javamxj_run '). value= ' Show Records ';    _logger = false; }}function togglediv () {& nbspvar e = $ ("Javamxj_log");    if (e) {      E.style.display = (E.style.display! = ' block ')? ' Block ': ' None ');   }}


The effect is as follows:

the problem: When used in IE, pay attention to the DOCTYPE declaration referenced by the parent HTML file if it is:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "HTTP://WWW.W3.ORG/TR/XHTML11/DTD/XHTML11.DTD" > It will disappear with the scroll bar under IE

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.