Middle
Do you have experience parsing logs? Can you write something to search for events in Nginx logs?
sobes.tech AI
Answer from AI
Yes, I have experience parsing logs. To find events in Nginx logs, you can write a simple script in Go that reads the log file and filters lines based on a specified condition.
Example: searching for all requests with a response code of 500 (server error).
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
file, err := os.Open("/var/log/nginx/access.log")
if err != nil {
panic(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Assume the response code is the 9th element separated by spaces
parts := strings.Fields(line)
if len(parts) > 8 && parts[8] == "500" {
fmt.Println(line)
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
This code opens the log, reads it line by line, and outputs only those lines where the HTTP status is 500. Similarly, you can search for other events, such as by IP, time, or URL.