LoginSignup
0
0

More than 3 years have passed since last update.

Node.jsを使ってサーバにアクセスログを出力してみた

Last updated at Posted at 2020-04-30

はじめに

この記事はなんとなくJSなどを勉強している学生がメモ代わりに書いている記事です。内容は期待しないでください。

1.仮想環境を構築する。

今回はUbuntuで行うのでiTerm2で仮想環境を起動する。

起動したところで
1.Virtual Box(バーチャルボックス)
2.Vagrant(ベイグラント)
という2つのソフトウェアを使った仮想環境でUbuntuを使用します。
cd ~/vagrant/ubuntu
vagrant up
vagrant ssh

Ubuntuがインストールされたディレクトリに移動。vagrant upは仮想的なPCにインストールされたUbuntuを起動するコマンドで,vagrant sshはVagrantの仮想マシンがセットされている状態でSSHに接続します。

2.作成したサーバにログを表示する

以下の内容をhttp.createServerのアロー関数内に記述します。
console.info(
'[' + new Date() + '] Requested by ' + reqest.connection.remoteAddress
);

今回はreqestという変数にサーバへのリクエストを代入しています。今回はリクエストが送られたIP情報を出力します。console.infoというものを使用していますがinfoは以下のように分類されます。

関数名 内容 出力
info,log 普段から残す情報 標準出力
warn,error 警告 エラー標準出力

3.作成したサーバにエラーを出力する

on('error', (e) => {
console.error('[' + new Date() + '] Server Error', e);

以上のon関数をアロー関数後に記述します。

4.実際にサーバを起動してみる

node ファイル名

実際にサーバを起動してエラー等のコンソールが表示されれば成功です。

0
0
0

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
0
0