輕松搞定Linux日志處理
現在很多人把Linux 配置成了一個開發工具,而用 Windows 來娛樂。你是Linux的使用者么?本文為你講解Linux日志處理方法,希望你能掌握Linux日志處理。每個使用UNIX/Linux的人都知道日志的用處,那你是否清楚Linux這些日志信息處理的來龍去脈呢?
我們可以看到Linux系統信息日志的途徑基本有以下2種:
(1)dmesg查看----這個命令比較常見
(2)/var/log/下的文件
那下面我們就從這個2個途徑著手,一步步的走下去.
(一)首先,我們來看dmesg這個常見的命令背后隱藏的是什么!!
(1)先讓我們來MAN一下這個家伙
-------------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日志處理了。
【編輯推薦】