Last active
January 20, 2025 04:11
-
-
Save mohamad-supangat/d3e8a6b3aa7afb0b040c56b203069dcc to your computer and use it in GitHub Desktop.
Parse Nginx Log.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "node:fs"; | |
fs.readFile("./nginx_log.txt", "utf8", (err, data) => { | |
const lines = data.split(/\r?\n/); | |
let reportsIP = {}; | |
let reportsDate = {}; | |
for (const line of lines) { | |
if (line) { | |
const ipAdress = line.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)[0]; | |
if (!reportsIP[ipAdress]) { | |
reportsIP[ipAdress] = { | |
totalAkses: 0, | |
logs: [], | |
}; | |
} | |
reportsIP[ipAdress]["totalAkses"]++; | |
const dateString = line.match(/\[(.*?)\]/)[1]; | |
const dates = dateString.match(/(\d{2})\/(\w{3})\/(\d{4})/); | |
const day = dates[1]; | |
const month = dates[2]; | |
const year = dates[3]; | |
const date = `${year}-${month}-${day}`; | |
if (!reportsDate[date]) { | |
reportsDate[date] = { | |
totalAkses: 0, | |
ip: [], | |
}; | |
} | |
reportsDate[date]["totalAkses"]++; | |
if (reportsDate[date]["ip"].indexOf(ipAdress) === -1) { | |
reportsDate[date]["ip"].push(ipAdress); | |
} | |
reportsIP[ipAdress]["logs"].push(line); | |
} | |
} | |
console.log( | |
JSON.stringify({ | |
reportsDate, | |
reportsIP, | |
}), | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment