大家可能都有管理日志的需要,比如定时压缩日志,或者当日志超过一定大小时就自动分裂成两个文件等。最近就接到这样一个小任务。我们的程序用的是C语言,用log4cpp的library来实现日志记录。但是问题是log4cpp并不支持当日志超过一定大小时自动分裂的功能,只能从头覆盖之前的日志,但这显然不是我们想要的。经过一番搜索,我发现其实Linux自带的logrotate命令就能够实现这样的功能。

这是logrotate的一段简介:

The logrotate utility is designed to simplify the administration of log files on a system which generates a lot of log files. Logrotate allows for the automatic rotation compression, removal and mailing of log files. Logrotate can be set to handle a log file daily, weekly, monthly or when the log file gets to a certain size.

为了使用它,主要有两个地方需要修改一下:一个是/etc/logrotate.conf,另一个是/etc/logrotate.d/下面的文件。

你既可以在logrotate.conf中直接定义如何处理你的log文件,也可以在/logrotate.d/下面针对自己的log新建一个对应的文件来定义处理log的行为。

这里是logrotate命令的详细解释的链接:http://linuxcommand.org/man_pages/logrotate8.html

下面是一个具体例子:

/var/log/news/news.crit {
monthly
rotate 2
olddir /var/log/news/old
missingok
postrotate
kill -HUP ‘cat /var/run/inn.pid‘
endscript
nocompress
}

monthly:说明是一个月进行一次处理,常用的还有daily,weekly

rotate 2:意思是说最多保留两个备份,多余的老的日志就被覆盖了

olddir:定义了旧的日志存储在哪里

missingok:意思是如果上述news.crit文件找不到的话也不报错,直接跳过

postrotate ... endscript:它们以及中间的命令定义了在执行完rotate之后要做什么,一般主要是为了让使用该日志文件的程序知道这个日志被替换了,需要重新打开这个文件

nocompress:说明旧日志不需要被压缩保存

logrotate定义了如何处理日志,而它本身则是被crond定时调用的。crond是一个Unix系操作系统中的定时调度软件,下面一段文字是从wiki上抄来的:

The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like connecting to the Internet and downloading email at regular intervals.

默认的logrotate是一天运行一次,它的脚本被放在/etc/cron.daily/下面。除了cron.daily外还有cron.weekly,cron.monthly,cron.hourly等分别对应不同的频率,你可以根据自己的需要把脚本放在不同的文件夹下面。在设置外所有东西以后,别忘了使用chkconfig crond on来保证它会一直开机运行。然后就大工告成了。

最新文章

  1. MongoDB的TruncationException异常解决方法
  2. SharePoint2013的头像显示和读取
  3. [转]使用Oracle SQL Developer 17410 提示无法从套接字获取更多数据如何解决
  4. (转)linux下vi命令大全
  5. C语言操作文件
  6. 7.Android常用第三方支付
  7. 关于http断点续传相关的RANGE这个header
  8. BigPipe
  9. 非常有用的Java程序片段
  10. 【HDOJ】2195 Monotone SE Min
  11. OCP-1Z0-051-题目解析-第29题
  12. Build FFmpeg for iOS
  13. labview生成可执行文件
  14. 华为机试题【10】-求数字基root
  15. [区块链] 带你进入Bitcoin开发 - 环境搭建
  16. mysql查看每个数据库所占磁盘大小
  17. ::class 意思
  18. [MS] 微软官网下载安装SQLSERVER2019的rpm
  19. JIT编译器技术理解
  20. MongoDB 之 Limit 选取 Skip 跳过 Sort 排序 MongoDB - 7

热门文章

  1. PHP 替换标签和标签内的内容
  2. jquery 基础教程[温故而知新二]
  3. cocos2d-x之 利用富文本控件解析xhml标签(文字标签,图片标签,换行标签,标签属性)
  4. Ganglia安装扩容
  5. 原来今天是感恩节-Linux基础继续&MySQL和PHP
  6. 150923-碎觉要-PHP,Linux
  7. AngularJS笔记---数据绑定
  8. Eclipse调试Bug的七种常用技巧
  9. 2015 Selenium大会
  10. Windows 常用 CMD 命令行介绍