HTTP日誌清除

服務器http服務的日誌大小2.4G,需適當清除
查看/var目錄大文件
find /var -size +500M |xargs du -h

sed -i '1,1000000d' /var/log/httpd/access_log
此方式在文件大時會佔用較多內存及磁盤
tail -n 100000 access_log > access_log

也可以將日誌進行切割

對於大日誌分割的幾種方法
當日志容量上G的時候,用vi查看具體內容效率就會變得特別低,這個時候就需要將大日誌進行分割。
爲了比較各種分割方法的效果,我選取的測試日誌基本信息如下:

ls -lrth test.log

-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log

wc -l test.log

8856340 test.log

  1. split方法分割
    split命令專門用來將一個大文件分割成很多個小文件,我把split命令的選項做一個簡要說明

選項 含義
-b 分割後的文檔大小,單位是byte
-C 分割後的文檔,單行最大byte數
-d 使用數字作爲後綴,同時使用-a length指定後綴長度
-l 分割後文檔的行數
爲了儘量保證日誌的可讀性,我們按行分割大日誌文件,並且指定分割後的文件的前綴和後綴

#後綴是數字,佔兩位,前綴是test.log
split -l 1000000 test.log -d -a 2 test.log
#分割之後的結果
ls -lrth
總用量 1.3G
-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log00
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log01
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log02
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log03
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log04
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log05
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log06
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log07
-rw-r--r-- 1 root root 64M 5月 30 20:55 test.log08

  1. dd分割
    dd bs=1M count=300 if=test.log of=newlog.1
    dd bs=1M count=300 if=test.log of=newlog.2 skip=300
    dd bs=1M count=300 if=test.log of=newlog.3 skip=600

分割後的效果

ls -lrth
總用量 1.3G
-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log
-rw-r--r-- 1 root root 300M 5月 30 21:07 newlog.1
-rw-r--r-- 1 root root 300M 5月 30 21:07 newlog.2
-rw-r--r-- 1 root root 45M 5月 30 21:07 newlog.3

在上面使用的命令中,bs代表數據塊的大小,count表示複製的塊數,if表示輸入文件,of表示輸出文件。
這個命令不能一下就把文件分割到我們想要的狀態,而且很有可能一行日誌被分到兩個文件中。

  1. head+tail分割
    用這兩個命令獲取文件部分內容,然後重定向就能實現文件分割,但是限制也挺多,只能把文件分成兩部分,如果文件特別大,想要達到預期的效果,就要一直分割下去。
    head/tail -n $行數 test.log > newlog
    因爲這兩個命令都比較熟悉,不再多講。

  2. sed實現分割
    實現原理就是用sed截取特定行之間的內容,然後進行重定向。

sed -n '1,2000000p' test.log > test.log.1
sed -n '2000001,4000000p' test.log > test.log.2
sed -n '4000001,6000000p' test.log > test.log.3
sed -n '6000001,8000000p' test.log > test.log.4
sed -n '8000001,$p' test.log > test.log.5

$表示最後一行,這個如果分割過多,也需要一個循環。

  1. awk實現分割
    實現原理和sed差不多,因爲使用awk不多,這裏只舉一個小例子:

awk ‘{if (NR<120000) print $0}’ test.log > a.txt
awk ‘{if (NR>=120000) print $0}’ test.log > b.txt

還是split用得舒服。

參考博客:http://blog.csdn.net/wind0513/article/details/5871293

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章