Logger


JavaScriptで込み入ったクラスを作ってたらだんだんデバッグが難しくて泣けてきました。FirefoxのDOM InspectorとかJavaScriptコンソールとかでデバッグするにも限界がありますね。IEと挙動が違う場合に対応しにくいし。


で、しょうがないのでLoggerを導入することに。またもや探したけれど見つからずまた作っちゃいました。こんな感じ。

function LogWindow(name) {
  
  this._name = name;
  
  this._window = null;
  
  this.debug = function( msg ) {
    try{ 
      this._write(msg);
    } catch(e) {
      this._window = null;
      this._write(msg);
    }
  }
  
  this._write = function( msg ){
    var w = this.getWindow();
    w.document.write( "
" ); w.document.write( this.formatDate( new Date() ) ); w.document.write( " [" + this._name + "] "); w.document.write( msg ); w.document.write( "\n" ); w.scrollBy(0, 1000); } this.formatDate = function( d ){ return d.getYear()+ "/"+ (d.getMonth() + 1)+ "/"+ d.getDate()+ " "+ d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ":" + d.getMilliseconds(); } this.getWindow = function(){ if (this._window == null){ this._window = window.open('', this._name, "scrollbars=yes"); this._window.moveTo(0,0); this._window.document.clear(); } else if (this._window.closed){ this._window.open(); } return this._window; } }

commons-loggingを意識したつもり。
使い方はこんな感じ。

var logger = new LogWindow("NaviMenu");
logger.debug("hoge");

debugメソッドが呼ばれたときにデバッグ用のウィンドウがなければ勝手に作って、そこにログのメッセージを日付付きで表示していきます。勝手にスクロールするので、tailしているみたいな感じで見えます。