Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
50
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

node.jsでログをファイル出力する

ロギングは設定が簡単なlog4jsを使用します。

log4jsインストール

npm install log4js --save

ログ設定ファイルを作る

vi logger.js

filenameの指定で「./」ここはプロジェクトルートをさすので注意

logger.js
var log4js = require('log4js');
var logger = exports = module.exports = {};
log4js.configure({
     appenders: [
         {
             "type": "file",
             "category": "request",
             "filename": "./logs/request.log",
             "pattern": "-yyyy-MM-dd"
         }
    ]
});

logger.request = log4js.getLogger('request');

logsディレクトリを作る

mkdir logs

ログ出力してみる!

vi index.js
index.js
var express = require('express');
var router = express.Router();
var logger = require('./logger');


router.get('/', function(req, res) {
  logger.request.info('url:'+ decodeURI(req.url));
  res.send(200);
});

ログファイルを確認

[2014-09-22 18:34:58.943] [INFO] request - http://localhost:3000/

ok!

まとめ

  • 設定ファイルのfilenameパス設定ではまった...
  • シンプルで使いやすい
  • 次はfluentd と組み合わせてログ活用したい
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
50
Help us understand the problem. What are the problem?