上記を参考に、以下のように書いてみた。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <button type="button" onClick="log.error('LOG1','LOG2' );">TEST ERROR</button> <button type="button" onClick="log.warn('LOG1','LOG2' );">TEST WARN</button> <button type="button" onClick="log.info('LOG1','LOG2' );">TEST INFO</button> <button type="button" onClick="log.debug('LOG1','LOG2' );">TEST DEBUG</button> </body> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/Logger.js"></script> <script> $(document).ready(function(){ // log.set_level('none'); //必要であれば、出力ログレベルを設定 }); </script> </html>
(function() { var Logger = function(){ this.level = this.LEVEL['info']; // set default disp level }; Logger.prototype = { LEVEL : {none:0, error:1, warn:2, info:3, debug:4 }, SERVER_LOG_URL : '/client_log.png', //設定値があれば、サーバへログ送信 set_level: function(lavel){ this.level = this.LEVEL[lavel]; }, error : function(){ this._log(arguments.callee.name,this._args2array(arguments)); }, warn : function(){ this._log(arguments.callee.name,this._args2array(arguments)); }, info : function(){ this._log(arguments.callee.name,this._args2array(arguments)); }, debug : function(){ this._log(arguments.callee.name,this._args2array(arguments)); }, _is_disp: function( level ){ //console objや、log levelの確認 if(window.console && typeof window.console[level] === 'function' && this.level >= this.LEVEL[level] ){ return true; } return false; }, _log: function(func_name, msgs){ if(! this._is_disp(func_name)) return; console[func_name]( msgs.join(' ')); if(this.SERVER_LOG_URL ){ this._log_to_server(func_name, msgs); return; } }, _log_to_server: function(func_name, msgs){ //サーバへログ送信 var msgs_str = func_name +'='+ msgs.join('_'); var now = (new Date()).getTime() + Math.random() * 1000 ; var url = this.SERVER_LOG_URL +'?'+ encodeURI(msgs_str) +"&time="+now; var dummy_img = new Image(); dummy_img.src = url; }, _args2array : function(arguments){ //可変長引数対応の為、Array型に変換 var ret = []; for (var i = 0; i < arguments.length; i++) { ret.push(arguments[i]); } return ret; } }; window.log = new Logger(); })();