How to Manage Visitor Log in Express.js

example code in here

Overview

log


Pre Install


Define Libraries

// visitor count example
// use '127.0.0.1:port' for this app
// this app didn't save log, if you want to maintain the log, you must have to save the log as file or database.

const moment = require('moment');

const express = require('express');
const expressLess = require('express-less');
const jade = require('jade');
const app = express();

// express middleware
const session = require('express-session');
const cookieParser = require('cookie-parser');

const PORT = 5001;

const access = {};

Graph for Access Log Stream (Saturn)

/*
 *  in real server, this is not needed!
 *
 *  graph will be updated
 *  when somebody visit http://115.88.201.7:5001 or http://115.88.201.7:5001/subpage
 *
 *  you can use for updating example graph by below bash script

    #!/bin/bash
    for i in {1..10}
    do
        number=$RANDOM
        if [ $number -gt 16000 ]
        then
            curl http://115.88.201.7:5001
        else
            curl http://115.88.201.7:5001/subpage
        fi
    done

 */

visualize = ()=> {
    // line color in graph
    const color = [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
    ];

    // Maxium log size for display (sec)
    const MAX_LOG_DISPLAY = 60;

    // add your page for logging access
    let pages = ['/', '/subpage'];

    // select access data, this will be changed to connecting database
    let times = [];
    for(let date in access) 
        times.push(date);

    // for performance in testing maintainance, remove past access log
    for(let i = 0 ; i < times.length - MAX_LOG_DISPLAY; i++) 
        delete access[times[i]];

    // select recent data
    times.splice(0, times.length - MAX_LOG_DISPLAY);

    // select display time, even if when visitor is zero
    let startTime = new Date(times[0]);
    let endTime = new Date(times[times.length - 1]);

    let timeShift = [];
    while(startTime.getTime() <= endTime.getTime()) {
        timeShift.push(moment(startTime).format('YYYY-MM-DD HH:mm:ss'));
        startTime = new Date(startTime.getTime() + 1000);
    }

    times = timeShift;
    times.splice(0, times.length - 60);

    // create chart data
    let chartData = {
        labels: times,
        datasets: []
    };

    // create chart.js dataset
    for(let j = 0 ; j < pages.length ; j++) {
        let page = pages[j];
        chartData.datasets.push({
            label: page,
            fill: false,
            borderColor: color[j % 6],
            borderWidth: 1,
            pointRadius: 0,
            data: []
        });
    }

    // add visit count to chart.js dataset
    for(let i = 0 ; i < times.length ; i++) {
        let date = times[i];
        for(let j = 0 ; j < pages.length ; j++) {
            let page = pages[j];
            if(access[date])
                chartData.datasets[j].data.push(access[date][page] ? access[date][page] : 0);
            else
                chartData.datasets[j].data.push(0);
        }
    }

    // update chart in saturn
    let chart = {
        id: 'visitor-log',
        width: 600,
        height: 300,
        type: 'line',
        data: chartData,
        options: {
            scales: {
                ticks: {
                    beginAtZero: true
                }
            }
        }
    };

    console.graph(chart);
}

Log Handling using Express Middleware

/*
 * update access log when every connection
 * by using express middleware
 */

app.use((req, res, next)=> {
    // this will update access log in memory
    // for maintaining log, you have to change this to inserting database
    let today = moment().format('YYYY-MM-DD HH:mm:ss');
    if(!access[today]) access[today] = {};
    if(!access[today][req.path]) access[today][req.path] = 0;
    access[today][req.path]++;

    // in real server, this is not needed
    visualize();

    next();
});

Express View

// use jade templates
app.set('views', './server/views');
app.set('view engine', 'jade');

// static
app.use('/static', express.static('./server/static'))

// less
app.use('/less', expressLess('./server/less'));

// use cookie & session
app.use(cookieParser());
app.use(session({
    secret: 'Saturn-SeCreT',
    resave: true,
    saveUninitialized: false
}));

// rendered page available at http://115.88.201.7:5001
// when you visit any page, it is written in access log
app.get('/', (req, res)=> {
    res.render('index', { title: 'Saturn', message: 'Hello there!'});
});

// rendered page available at http://115.88.201.7:5001/subpage
app.get('/subpage', (req, res)=> {
    res.render('index', { title: 'Subpage', message: 'Hello there!'});
});

Listen Express

app.listen(PORT, ()=> {
    console.log(`Example app listening on port ${PORT}!`)
});

댓글 남기기