blob: 82512c2c4aaca077decae8215eccfe57c93ad6b4 [file] [log] [blame]
Yufeng Shen5f23bbb2013-04-16 15:00:27 -04001#!/bin/sh
2
Steve Fung6c34c252015-08-20 00:27:30 -07003# Copyright (C) 2013 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Yufeng Shen5f23bbb2013-04-16 15:00:27 -040016
17# Usage example: "kernel_log_collector.sh XXX YYY"
18# This script searches logs in the /var/log/messages which have the keyword XXX.
19# And only those logs which are within the last YYY seconds of the latest log
20# that has the keyword XXX are printed.
21
Yufeng Shen4c9f5762013-06-19 16:50:37 -040022# Kernel log has the possible formats:
Yufeng Shen5f23bbb2013-04-16 15:00:27 -040023# 2013-06-14T16:31:40.514513-07:00 localhost kernel: [ 2.682472] MSG MSG ...
Yufeng Shen4c9f5762013-06-19 16:50:37 -040024# 2013-06-19T20:38:58.661826+00:00 localhost kernel: [ 1.668092] MSG MSG ...
Yufeng Shen5f23bbb2013-04-16 15:00:27 -040025
26search_key=$1
27time_duration=$2
Yufeng Shen4c9f5762013-06-19 16:50:37 -040028msg_pattern="^[0-9-]*T[0-9:.+-]* localhost kernel"
Yufeng Shen5f23bbb2013-04-16 15:00:27 -040029
30die() {
31 echo "kernel_log_collector: $*" >&2
32 exit 1
33}
34
35get_timestamp() {
36 timestamp="$(echo $1 | cut -d " " -f 1)"
37 timestamp="$(date -d "${timestamp}" +%s)" || exit $?
38 echo "${timestamp}"
39}
40
41last_line=$(grep "${msg_pattern}" /var/log/messages | grep -- "${search_key}" | tail -n 1)
42
43if [ -n "${last_line}" ]; then
44 if ! allowed_timestamp=$(get_timestamp "${last_line}"); then
45 die "coule not get timestamp from: ${last_line}"
46 fi
47 : $(( allowed_timestamp -= ${time_duration} ))
48 grep "${msg_pattern}" /var/log/messages | grep -- "${search_key}" | while read line; do
49 if ! timestamp=$(get_timestamp "${line}"); then
50 die "could not get timestamp from: ${line}"
51 fi
52 if [ ${timestamp} -gt ${allowed_timestamp} ]; then
53 echo "${line}"
54 fi
55 done
56fi
57
58echo "END-OF-LOG"
59