Log Analyzer Project in Java
In this guide, we'll create a Java program called Log Analyzer that processes and analyzes NGINX log files. We'll cover everything step-by-step so that even if you're a beginner, you'll be able to follow along, copy the code, run it, and see the results.
Table of Contents
- Prerequisites
- Project Setup
- Understanding the Requirements
- Writing the Code
- Compiling and Running the Program
- Testing the Program
- Additional Features
- Conclusion
Prerequisites
- Java Development Kit (JDK) 8 or higher: Make sure you have JDK installed. You can download it from Oracle's official website.
- Text Editor or IDE: You can use any text editor (like Notepad++) or an Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA.
Project Setup
-
Create a Project Directory
Create a new directory for your project. Let's call it LogAnalyzer.
mkdir LogAnalyzer
cd LogAnalyzer
-
Create the Java Source File
We'll keep all our code in a single Java file for simplicity.
touch Analyzer.java
Understanding the Requirements
Our program should:
- Accept command-line arguments:
--path: Path to one or more NGINX log files (can be a local path pattern or URL).
--from and --to (optional): Time range in ISO8601 format.
--format (optional): Output format (markdown or adoc).
- Perform the following analyses:
- Count total number of requests.
- Identify the most frequently requested resources.
- Identify the most frequently occurring response codes.
- Calculate average response size.
- Calculate the 95th percentile of response sizes.
- Output the results in the specified format.
- Process log files efficiently (without loading the entire file into memory).
Writing the Code
Let's start coding step by step.
Main Class
Create the Analyzer class and include the main method.
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.*;
public class Analyzer {
public static void main(String[] args) {
// Entry point of the program
}
}
Command-Line Argument Parsing
We'll parse the command-line arguments manually.
// Inside the main method
Map<String, String> params = parseArgs(args);
// Default values
String pathPattern = params.get("path");
String fromDateStr = params.get("from");
String toDateStr = params.get("to");
String format = params.getOrDefault("format", "markdown");
if (pathPattern == null) {
System.out.println("Please provide the --path argument.");
return;
}
Add the parseArgs method:
private static Map<String, String> parseArgs(String[] args) {
Map<String, String> params = new HashMap<>();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("--")) {
String key = args[i].substring(2);
String value = (i + 1) < args.length ? args[i + 1] : null;
if (value != null && !value.startsWith("--")) {
params.put(key, value);
i++;
} else {
params.put(key, null);
}
}
}
return params;
}
Reading Log Files
We'll handle both local files (with wildcards) and URLs.
// Inside the main method
List<String> logLines = new ArrayList<>();
// Check if pathPattern is a URL
if (isValidURL(pathPattern)) {
logLines.addAll(readLinesFromURL(pathPattern));
} else {
// Expand wildcards for local files
List<Path> paths = resolveLocalPaths(pathPattern);
for (Path path : paths) {
logLines.addAll(readLinesFromFile(path));
}
}
Add helper methods:
private static boolean isValidURL(String urlStr) {
try {
new URL(urlStr);
return true;
} catch (MalformedURLException e) {
return false;
}
}
private static List<String> readLinesFromURL(String urlStr) {
List<String> lines = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(urlStr).openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
lines.add(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
private static List<Path> resolveLocalPaths(String pathPattern) {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pathPattern);
List<Path> paths = new ArrayList<>();
Path startPath = Paths.get(".");
try (Stream<Path> stream = Files.walk(startPath)) {
stream.filter(matcher::matches)
.forEach(paths::add);
} catch (IOException e) {
e.printStackTrace();
}
return paths;
}
private static List<String> readLinesFromFile(Path path) {
List<String> lines = new ArrayList<>();
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
stream.forEach(lines::add);
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
Parsing Log Entries
We'll define a LogRecord class to represent each log entry.
class LogRecord {
String remoteAddr;
String remoteUser;
LocalDateTime timeLocal;
String request;
String method;
String url;
String protocol;
int status;
long bodyBytesSent;
String httpReferer;
String httpUserAgent;
// Constructor and other methods
}
Add a method to parse a log line:
private static LogRecord parseLogLine(String line) {
// NGINX log format:
// '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'
// Use regex to extract fields
String regex = "^(\\S+) - (\\S+) \\[(.+?)\\] \"(.+?)\" (\\d{3}) (\\d+) \"(.*?)\" \"(.*?)\"$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
LogRecord record = new LogRecord();
record.remoteAddr = matcher.group(1);
record.remoteUser = matcher.group(2);
String timeLocalStr = matcher.group(3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
record.timeLocal = LocalDateTime.parse(timeLocalStr, formatter);
record.request = matcher.group(4);
// Split request into method, url, and protocol
String[] requestParts = record.request.split(" ");
if (requestParts.length == 3) {
record.method = requestParts[0];
record.url = requestParts[1];
record.protocol = requestParts[2];
}
record.status = Integer.parseInt(matcher.group(5));
record.bodyBytesSent = Long.parseLong(matcher.group(6));
record.httpReferer = matcher.group(7);
record.httpUserAgent = matcher.group(8);
return record;
} else {
// Log line didn't match the expected format
return null;
}
}
Filtering Logs
We'll filter logs based on the from and to dates if provided.
// Inside the main method
List<LogRecord> logRecords = new ArrayList<>();
DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime fromDate = fromDateStr != null ? LocalDateTime.parse(fromDateStr, isoFormatter) : null;
LocalDateTime toDate = toDateStr != null ? LocalDateTime.parse(toDateStr, isoFormatter) : null;
for (String line : logLines) {
LogRecord record = parseLogLine(line);
if (record != null) {
boolean inRange = true;
if (fromDate != null && record.timeLocal.isBefore(fromDate)) {
inRange = false;
}
if (toDate != null && record.timeLocal.isAfter(toDate)) {
inRange = false;
}
if (inRange) {
logRecords.add(record);
}
}
}
Collecting Statistics
We'll collect the required statistics in one pass.
// Inside the main method
int totalRequests = 0;
Map<String, Integer> resourceCount = new HashMap<>();
Map<Integer, Integer> statusCount = new HashMap<>();
long totalResponseSize = 0;
List<Long> responseSizes = new ArrayList<>();
for (LogRecord record : logRecords) {
totalRequests++;
// Resource count
resourceCount.put(record.url, resourceCount.getOrDefault(record.url, 0) + 1);
// Status code count
statusCount.put(record.status, statusCount.getOrDefault(record.status, 0) + 1);
// Response sizes
totalResponseSize += record.bodyBytesSent;
responseSizes.add(record.bodyBytesSent);
}
Generating the Report
We'll format the output according to the specified format.
// Inside the main method
// Calculate average response size
double averageResponseSize = totalRequests > 0 ? (double) totalResponseSize / totalRequests : 0;
// Calculate 95th percentile
Collections.sort(responseSizes);
int index95 = (int) (0.95 * responseSizes.size());
long percentile95 = responseSizes.get(Math.min(index95, responseSizes.size() - 1));
// Prepare for output
StringBuilder report = new StringBuilder();
// Output in markdown format
if (format.equalsIgnoreCase("markdown")) {
generateMarkdownReport(report, params, totalRequests, averageResponseSize, percentile95, resourceCount, statusCount);
} else if (format.equalsIgnoreCase("adoc")) {
generateAdocReport(report, params, totalRequests, averageResponseSize, percentile95, resourceCount, statusCount);
} else {
System.out.println("Unknown format: " + format);
return;
}
// Print the report
System.out.println(report.toString());
Add methods to generate the report:
private static void generateMarkdownReport(StringBuilder report, Map<String, String> params, int totalRequests,
double averageResponseSize, long percentile95,
Map<String, Integer> resourceCount, Map<Integer, Integer> statusCount) {
// General Information
report.append("#### Общая информация\n\n");
report.append("| Метрика | Значение |\n");
report.append("|:---------------------:|-------------:|\n");
report.append("| Файл(-ы) | `" + params.get("path") + "` |\n");
report.append("| Начальная дата | " + params.getOrDefault("from", "-") + " |\n");
report.append("| Конечная дата | " + params.getOrDefault("to", "-") + " |\n");
report.append("| Количество запросов | " + totalRequests + " |\n");
report.append(String.format("| Средний размер ответа | %.2f b |\n", averageResponseSize));
report.append("| 95p размера ответа | " + percentile95 + " b |\n\n");
// Requested Resources
report.append("#### Запрашиваемые ресурсы\n\n");
report.append("| Ресурс | Количество |\n");
report.append("|:---------------:|-----------:|\n");
resourceCount.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(10)
.forEach(entry -> report.append("| `" + entry.getKey() + "` | " + entry.getValue() + " |\n"));
report.append("\n#### Коды ответа\n\n");
report.append("| Код | Имя | Количество |\n");
report.append("|:---:|:---------------------:|-----------:|\n");
statusCount.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.forEach(entry -> report.append("| " + entry.getKey() + " | " + getStatusName(entry.getKey()) + " | " + entry.getValue() + " |\n"));
}
private static void generateAdocReport(StringBuilder report, Map<String, String> params, int totalRequests,
double averageResponseSize, long percentile95,
Map<String, Integer> resourceCount, Map<Integer, Integer> statusCount) {
// Similar to markdown but with adoc syntax
// Implementation left for the reader
}
private static String getStatusName(int statusCode) {
// Map status codes to names
switch (statusCode) {
case 200:
return "OK";
case 404:
return "Not Found";
case 500:
return "Internal Server Error";
// Add more cases as needed
default:
return "-";
}
}
Compiling and Running the Program
-
Save the Code
Make sure all the code is saved in Analyzer.java.
-
Compile the Program
Open a terminal in the LogAnalyzer directory and run:
javac Analyzer.java
This will compile your Java program.
-
Run the Program
java Analyzer --path logs/access.log --format markdown
Replace logs/access.log with the path to your log file(s).
Testing the Program
-
Generate Sample Logs
Use the provided Docker command to generate sample NGINX logs:
docker run --rm -it -e 'RATE=100' kscarlett/nginx-log-generator >> logs/access.log
Wait for a few seconds and then press Ctrl+C to stop.
-
Run the Analyzer
java Analyzer --path logs/access.log --format markdown
-
Check the Output
You should see a report similar to the example provided.
Additional Features
Implementing Two Additional Statistics
Let's add:
- Top Client IP Addresses
- Most Used HTTP Methods
Modify the statistics collection code:
Map<String, Integer> ipCount = new HashMap<>();
Map<String, Integer> methodCount = new HashMap<>();
// Inside the loop
ipCount.put(record.remoteAddr, ipCount.getOrDefault(record.remoteAddr, 0) + 1);
methodCount.put(record.method, methodCount.getOrDefault(record.method, 0) + 1);
Add these to the report generation:
// After existing sections
// Top Client IP Addresses
report.append("\n#### Топ IP-адресов клиентов\n\n");
report.append("| IP-адрес | Количество |\n");
report.append("|:-----------------:|-----------:|\n");
ipCount.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(10)
.forEach(entry -> report.append("| " + entry.getKey() + " | " + entry.getValue() + " |\n"));
// Most Used HTTP Methods
report.append("\n#### HTTP методы\n\n");
report.append("| Метод | Количество |\n");
report.append("|:-----:|-----------:|\n");
methodCount.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(entry -> report.append("| " + entry.getKey() + " | " + entry.getValue() + " |\n"));
Implementing Filter by Field and Value
Add support for --filter-field and --filter-value arguments.
Update command-line parsing:
String filterField = params.get("filter-field");
String filterValue = params.get("filter-value");
Update the filtering logic:
boolean matchesFilter = true;
if (filterField != null && filterValue != null) {
if (filterField.equalsIgnoreCase("agent")) {
matchesFilter = record.httpUserAgent.contains(filterValue);
} else if (filterField.equalsIgnoreCase("method")) {
matchesFilter = record.method.equalsIgnoreCase(filterValue);
}
// Add more fields as needed
}
if (inRange && matchesFilter) {
logRecords.add(record);
}
Now you can run:
java Analyzer --path logs/access.log --filter-field method --filter-value GET
Conclusion
You've now built a complete log analyzer in Java that can process NGINX logs, filter them based on date ranges or specific fields, collect various statistics, and output the results in Markdown format.
Feel free to extend the program further by adding more features or improving the existing code.
Note: Make sure to handle exceptions and edge cases in a production environment. This example is simplified for educational purposes.