В dmesg содержатся сообщения ядра, позволяющие диагностировать ошибки в системе. По умолчанию вывод выглядит следующим образом:
[ 0.217507] TCP established hash table entries: 65536 (order: 8, 1048576 bytes)
[ 0.217762] TCP bind hash table entries: 65536 (order: 8, 1048576 bytes)
[ 0.217941] TCP: Hash tables configured (established 65536 bind 65536)
[ 0.218034] TCP: reno registered
[ 0.218112] UDP hash table entries: 4096 (order: 5, 131072 bytes)
[ 0.218211] UDP-Lite hash table entries: 4096 (order: 5, 131072 bytes)
[ 0.218344] NET: Registered protocol family 1
[4315224.110087] r8169 0000:04:00.0 eth0: link down
[4315230.097079] r8169 0000:04:00.0 eth0: link up
В начале каждой строки указано время, прошедшее с момента старта системы, до наступления события. Оценить продолжительность отсутствия линка на интерфейсе eth0 в примере выше - нетривиальная задача. Гораздо проще сделать это, переведя время в человеку понятный формат.
В Debian-like для этого достаточно вывести вместо dmesg содержимое /var/log/kern.log. В дистрибутивах на основе RedHat подобного лога нет, поэтому можно прибегнуть к использованию perl или python скриптов-интерпретаторов.
dmesg.pl
#!/usr/bin/perl
use strict;
use warnings;
my @dmesg_new = ();
my $dmesg = "/bin/dmesg";
my @dmesg_old = `$dmesg`;
my $now = time();
my $uptime = `cat /proc/uptime | cut -d"." -f1`;
my $t_now = $now - $uptime;
sub format_time {
my @time = localtime $_[0];
$time[4]+=1; # Adjust Month
$time[5]+=1900; # Adjust Year
return sprintf '%4i-%02i-%02i %02i:%02i:%02i', @time[reverse 0..5];
}
foreach my $line ( @dmesg_old )
{
chomp( $line );
if( $line =~ m/\[\s*(\d+)\.(\d+)\](.*)/i )
{
# now - uptime + sekunden
my $t_time = format_time( $t_now + $1 );
push( @dmesg_new , "[$t_time] $3" );
}
}
print join( "\n", @dmesg_new );
print "\n";
dmesg.py
#!/usr/bin/env python
# coding=utf8
# Copyright (C) 2010 Saúl ibarra Corretgé <saghul@gmail.com>
#
"""
pydmesg: dmesg with human-readable timestamps
"""
from __future__ import with_statement
import re
import subprocess
import sys
from datetime import datetime, timedelta
_datetime_format = "%Y-%m-%d %H:%M:%S"
_dmesg_line_regex = re.compile("^\[(?P\d+\.\d+)\](?P.*)$")
def exec_process(cmdline, silent, input=None, **kwargs):
"""Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
Optionally prints stdout and stderr while running."""
try:
sub = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
stdout, stderr = sub.communicate(input=input)
returncode = sub.returncode
if not silent:
sys.stdout.write(stdout)
sys.stderr.write(stderr)
except OSError,e:
if e.errno == 2:
raise RuntimeError('"%s" is not present on this system' % cmdline[0])
else:
raise
if returncode != 0:
raise RuntimeError('Got return value %d while executing "%s", stderr output was:\n%s' % (returncode, " ".join(cmdline), stderr.rstrip("\n")))
return stdout
def human_dmesg():
now = datetime.now()
uptime_diff = None
try:
with open('/proc/uptime') as f:
uptime_diff = f.read().strip().split()[0]
except IndexError:
return
else:
try:
uptime = now - timedelta(seconds=int(uptime_diff.split('.')[0]), microseconds=int(uptime_diff.split('.')[1]))
except IndexError:
return
dmesg_data = exec_process(['dmesg'], True)
for line in dmesg_data.split('\n'):
if not line:
continue
match = _dmesg_line_regex.match(line)
if match:
try:
seconds = int(match.groupdict().get('time', '').split('.')[0])
nanoseconds = int(match.groupdict().get('time', '').split('.')[1])
microseconds = int(round(nanoseconds * 0.001))
line = match.groupdict().get('line', '')
t = uptime + timedelta(seconds=seconds, microseconds=microseconds)
except IndexError:
pass
else:
print "[%s]%s" % (t.strftime(_datetime_format), line)
if __name__ == '__main__':
human_dmesg()
Необходимо сохранить этот текст с помощью любого текстового редактора в систему, сделать скрипт исполняемым с помощью команды chmod +x ИмяФайла и запустить его.
Есть альтернативный вариант, который не всегда работает, но требует меньше времени на реализацию - выполнить следующий однострочный скрипт:
dmesg|perl -pE '/\[\s*(\d+\.\d+)\]/; $t=scalar localtime time-$1/100; s/\[\s*(\d+\.\d+)\]/[$t]/;'
Ссылки: