15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

console.log は長くてつらい

Last updated at Posted at 2012-12-26

console.(log|error|warn|info|debug) を短い奴に再定義したい時は、こんな感じ。

var log = console.log.bind(console);

動かない例

var log = console.log

↑これで、log('foo'); とかやってみても、例外でてダメ。
console.log とはレシーバーが違ってしまうせいかも。

動くけど・・・

var log = function(o){ console.log(o); }

↑これは、動く。でもconsole.log の可変長引数な仕組みを潰してるので勿体無い。

ブラウザ互換とか考えると

こんな感じ?他になにかいい方法ありませんかね。

var methods = ['log', 'warn', 'error', 'info', 'debug', 'dir'];
for (var i in methods){
  (function(m) {
    if (console[m]) {
      window[m] = console[m].bind(console); };
    } else {
      window[m] = log;
    }
  })(methods[i]);
}

log('hoge');
warn('fuga');
error('piyo');
info('nyan');
debug('wan');

メソッド存在チェックして、無かったら console.log を使う感じにしてる。

ここまで来たら、ログレベルを定義して、レベル低い出力は抑制する仕組みを作るの簡単そうですね。専用のライブラリ使ったほうが良い気もしますが。

15
15
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?