1
2

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.

Apacheでアクセスログを取ってみる。

Last updated at Posted at 2020-01-02

※MacOS

Apacheってなに

Webサーバのソフト のこと
HTMLや画像、動画などの静的コンテンツを返してくれるもの

今回使用するファイル

Apache_Test
  ├── app.js
  ├── node_modules
  │   └── たくさんあるから書かない 
  ├── package.json
  └── httpd.conf 

Installation

$ npm init -y
$ npm i express fs morgan

実際にやってみる

処理内容

app.js
const app = require('express')()
const morgan = require('morgan')
const fs = require('fs')
const port = process.env.PORT || 8080

let accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
app.use(morgan('combined', {stream: accessLogStream}))
app.get('/', function (req, res) {
  res.send("Hello Node.js!")
})
app.listen(port, ()=> console.log("Port number is "+ port))

走らせる

$ node app.js
Port number is 8080.

ローカルサーバにアクセス

localhost:8080
スクリーンショット 2020-01-03 2.39.36.png

このように app.js で指定した文言が表示されていればアクセスは成功

アクセスログ取得

今回設定したポート番号へのアクセスを計測する。

httpd.confの設定

NameVirtualHost *:8080
Listen 8080
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"

このconfigファイルではログの出力形式を指定することができる。

今回は %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"

%h   リモートホスト名
%l   クライアントの識別子
%u   認証ユーザー名
%t   リクエストを受信した時刻
%r   リクエストの最初の行
%>s  最後のレスポンスのステータス
%b   HTTPヘッダを除くレスポンスのバイト数
%{Referer}i     サーバが受信したリクエストヘッダのReferer
%{User-Agent}i  サーバが受信したリクエストヘッダのUser-Agent

とする。

もう一度走らせる

$ node app.js
Port number is 8080.

もう一度ローカルサーバにアクセス

ファイル構造を確認してみると、、、 access.logというファイルが吐き出されているはず!

access.logの確認

httpd.conf で指定した通りにアクセスログが吐き出されている。

終わり

今回使用したコードはこちら

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?