歡迎您光臨本站 註冊首頁

新手學堂:摸清Linux日誌處理的來龍去脈

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

每個使用UNIX/LINUX的人都知道日誌的用處,那你是否清楚LINUX這些日誌信息處理的來龍去脈呢?

我們可以看到LINUX系統信息日誌的途徑基本有以下2種:

(1)dmesg查看----這個命令比較常見

(2)/var/log/下的文件

那下面我們就從這個2個途徑著手,一步步的走下去.

(一)

首先,我們來看dmesg這個常見的命令背後隱藏的是什麼!!

(1)先讓我們來MAN一下這個傢伙

-------------man dmesg--------------------------

-------------man dmesg--------------------------

NAME

dmesg - print or control the kernel ring buffer

SYNOPSIS

dmesg [ -c ] [ -n level ] [ -s bufsize ]

DESCRIPTION

dmesg is used to examine or control the kernel ring

buffer.

The program helps users to print out their bootup mes-

sages. Instead of copying the messages by hand, the user

need only:

dmesg > boot.messages

and mail the boot.messages file to whoever can debug their

problem.

OPTIONS

-c Clear the ring buffer contents after printing.

-sbufsize

Use a buffer of size bufsize to query the kernel

ring buffer. This is 16392 by default. (The

default kernel syslog buffer size was 4096 at

first, 8192 since 1.3.54, 16384 since 2.1.113.) If

you have set the kernel buffer to be larger than

the default then this option can be used to view

the entire buffer.

-nlevel

Set the level at which logging of messages is done

to the console. For example, -n 1 prevents all

messages, expect panic messages, from appearing on

the console. All levels of messages are still

written to /proc/kmsg, so syslogd(8) can still be

used to control exactly where kernel messages

appear. When the -n option is used, dmesg will not

print or clear the kernel ring buffer.

When both options are used, only the last option on

the command line will have an effect.

從LINUX提供的手冊,我們可以得知一條最重要的信息dmesg是從kernel 的ring buffer(環緩衝區)中讀取信息的.

(2)那什麼是ring buffer呢?

在LINUX中,所有的系統信息(包內核信息)都會傳送到ring buffer中.而內核產生的信息由printk()列印出來.系統啟動時所看到的信息都是由該函數列印到屏幕中. printk()打出的信息往往以 <0><2>...這的數字錶明消息的重要級別.高於一定的優先順序別會列印到屏幕上, 否則只會保留在系統的緩衝區中(ring buffer).

至於dmesg具體是如何從ring buffer中讀取的,大家可以看dmesg.c源代碼.很短,比較容易讀懂.

(二)

dmesg怎麼搞的大家應該很明白了吧.至於/var/log/下的文件更是大家熟悉得不能再熟悉了!

(1)/var/log/..下為什麼有這麼多文件呢?

一句話解釋: 是syslogd這個守護進程根據/etc/syslog.conf,將不同的服務產生的Log記錄到不同的文件中.

這裡的/etc/syslog.conf我就不細說了,很多這方面的信息(去查吧).

(2)既然知道了,/var/log/..是由syslogd這個守護進程產生的.那就再順著這條線走下去.

LINUX系統啟動后,由/etc/init.d/sysklogd先後啟動klogd,syslogd兩個守護進程.

其中klogd會通過syslog()系統調用或者讀取proc文件系統來從系統緩衝區(ring buffer)中得到由內核printk()

發出的信息.而syslogd是通過klogd來讀取系統內核信息.

我想至此,大家心理應該對log產生,讀取等一系列的動作有所感覺.

總結

(1)所有系統信息是輸出到ring buffer中去的.dmesg所顯示的內容也是從ring buffer中讀取的.

(2)LINUX系統中/etc/init.d/sysklogd會啟動2個守護進程:Klogd&&Syslogd

(3)klogd是負責讀取內核信息的,有2種方式:

syslog()系統調用(這個函數用法比較全,大家去MAN一下看看)

直接的對/proc/kmsg進行讀取(再這提一下,/proc/kmsg是專門輸出內核信息的地方)

(4)Klogd的輸出結果會傳送給syslogd進行處理,syslogd會根據/etc/syslog.conf的配置把log

信息輸出到/var/log/下的不同文件中.


[火星人 ] 新手學堂:摸清Linux日誌處理的來龍去脈已經有442次圍觀

http://coctec.com/docs/linux/show-post-57337.html