-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_log.sh
63 lines (49 loc) · 1.39 KB
/
parse_log.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/bin/bash
usage() {
echo "Usage: $0 -f <logfile> [-d <date>] [-k <keyword>] [-l <loglevel>] [-o <outputfile>]"
echo " -f: Path to the log file"
echo " -d: Filter logs by date (e.g., 2024-12-09)"
echo " -k: Filter logs by keyword (e.g., 'ERROR')"
echo " -l: Filter logs by log level (e.g., 'INFO', 'DEBUG', 'ERROR')"
echo " -o: Save filtered logs to output file (optional)"
exit 1
}
while getopts "f:d:k:l:o:" opt; do
case "$opt" in
f) LOGFILE="$OPTARG" ;;
d) DATE="$OPTARG" ;;
k) KEYWORD="$OPTARG" ;;
l) LOGLEVEL="$OPTARG" ;;
o) OUTPUTFILE="$OPTARG" ;;
*) usage ;;
esac
done
# Ensure logfile is provided
if [ -z "$LOGFILE" ]; then
echo "Error: Log file is required."
usage
fi
# Check if the log file exists
if [ ! -f "$LOGFILE" ]; then
echo "Error: Log file '$LOGFILE' not found."
exit 1
fi
FILTER_CMD="cat $LOGFILE"
if [ -n "$DATE" ]; then
FILTER_CMD="$FILTER_CMD | grep '$DATE'"
fi
if [ -n "$KEYWORD" ]; then
FILTER_CMD="$FILTER_CMD | grep '$KEYWORD'"
fi
if [ -n "$LOGLEVEL" ]; then
FILTER_CMD="$FILTER_CMD | grep '$LOGLEVEL'"
fi
echo "Running filter command: $FILTER_CMD"
FILTERED_LOGS=$(eval "$FILTER_CMD")
if [ -n "$OUTPUTFILE" ]; then
echo "$FILTERED_LOGS" > "$OUTPUTFILE"
echo "Filtered logs saved to '$OUTPUTFILE'."
else
echo "Filtered logs:"
echo "$FILTERED_LOGS"
fi