使用Logrotate管理日志

文章目录

[隐藏]

  • Logrotate功能
  • Logrotate配置
  • httpd
  • 排障
  • 最后

Linux使用某些软件的时候会产生日志文件,而这些软件本身对日志不进行分割或者压缩处理,久而久之会导致日志文件异常巨大,影响机器性能,配置不高的机器上尤为严重。而logrotate就是管理这些日志文件的神器。

Logrotate功能

logrotate会周期性的读,压缩,备份,创建新的日志文件。你想对日志文件做的操作,它基本上可以做到。

  • 防止单个日志文件过于庞大

  • 删除旧的日志文件,以防旧日志文件填满你的磁盘。

  • 对单个日志文件或者某个目录下的文件按时间/大小进行切割,压缩操作;指定日志保存数量;还可以在切割之后运行自定义命令。

许多Linux软件都已经内置了logrotate了,例如httpd默认就使用logrotated来帮你管理日志文件。

httpd logrotate

Logrotate配置

1.首先看logrotate软件包的内容

logrotate包目录

一般第三方软件包的日志文件管理都放在/etc/logrotate.d目录下。

httpd
[[email protected] nginx]# cat /etc/logrotate.d/httpd/var/log/httpd/*log {      daily      missingok      notifempty      sharedscripts      delaycompress      postrotate          /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true      endscript  }  

这份配置会处理/var/log/httpd/目录下后缀为log的文件。

  • monthly: 日志文件将按月轮循。其它可用值为‘daily’,‘weekly’或者‘yearly’。

  • missingok: 在日志轮循期间,任何错误将被忽略,例如“文件无法找到”之类的错误。

  • notifempty: 如果日志文件为空,轮循不会进行。

  • sharedscripts: 在所有的日志文件都轮询之后运行postrotate脚本,如果没设置默认会在每个匹配的文件轮询之后运行一次postrotate脚本。

  • compress: 在轮循任务完成后,已轮循的归档将使用gzip进行压缩。

  • delaycompress: 总是与compress选项一起用,delaycompress选项指示logrotate不要将最近的归档压缩,压缩将在下一次轮循周期进行。这在你或任何软件仍然需要读取最新归档时很有用。

  • postrotate/endscript: 在所有其它指令完成后,postrotate和endscript里面指定的命令将被执行。在这种情况下,rsyslogd 进程将立即再次读取其配置并继续运行。

这里解释仅做参考,logrotate中的每个参数可单独进行搜索,明确具体的含义,man手册中也有详细说明。

排障
logrotate [-dv] [-f|--force] [-s|--state file] config_file  [[email protected] nginx]# logrotate --help用法: logrotate [OPTION...] <configfile>    -d, --debug               Don't do anything, just test (implies -v)    -f, --force               Force file rotation    -m, --mail=command        Command to send mail (instead of `/bin/mail')    -s, --state=statefile     Path of state file    -v, --verbose             Display messages during rotation    -l, --log=STRING          Log file    --version                 Display version information  

1.以debug模式运行某个logrotate配置文件

logrotate debug模式

2.强制使用logrotate近轮询日志文件

logrotate 强制轮询

3.logrotate记录轮询状态的文件

logrotate状态文件格式

记录某轮询日志到logrotate状态文件中

logrotate -vf -s /var/lib/logrotate/logrotate.status  /etc/logrotate.d/httpd  
最后

logrotate在日志处理上功能十分强大,但却十分容易上手,本文只是作为抛砖引玉的作用。在使用logrotate的时候,根据man手册可查寻找想要了解的各种配置信息。

希望能帮助到大家。

原文出处:imooc -> https://www.imooc.com/article/259210

本站所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如果侵犯你的利益,请发送邮箱到 [email protected],我们会很快的为您处理。