Linux日志管理和日志级别

在 Linux 系统里,日志主要通过 syslog(或新一代 rsyslog/journald)来统一管理。不同的系统组件、服务和应用程序会把日志写到 syslog,再由 syslogd 按照规则分发到不同文件或远程主机。


一、常见日志存放路径

  • 系统日志/var/log/messages/var/log/syslog
  • 认证/安全日志/var/log/secure/var/log/auth.log
  • 内核日志/var/log/kern.log
  • 邮件日志/var/log/maillog
  • 计划任务日志/var/log/cron
  • 应用日志:常见如 Nginx /var/log/nginx/, MySQL /var/log/mysql/

二、syslog 日志级别(按严重程度从高到低)

数字越小,严重性越高;越往下是信息性/调试日志。

数值 级别名 含义
0 emerg 紧急,系统不可用 (System is unusable)
1 alert 必须立即处理 (Action must be taken immediately)
2 crit 严重情况 (Critical conditions)
3 err / error 错误 (Error conditions)
4 warn / warning 警告 (Warning conditions)
5 notice 一般重要情况 (Normal but significant)
6 info 信息性消息 (Informational)
7 debug 调试信息 (Debug-level messages)

👉 一般生产环境推荐:

  • 系统日志保留 info 以上(即 0–6)
  • 开发环境可能需要打开 debug

三、日志管理方式

  1. rsyslog 配置
    配置文件:/etc/rsyslog.conf/etc/rsyslog.d/*.conf
    格式:

    facility.priority    /var/log/xxx.log
    
    • facility:日志来源(如 auth, cron, daemon, kern, mail, syslog, user, local0-7
    • priority:日志级别(如 err, info

    例如:

    authpriv.*        /var/log/secure
    *.info;mail.none;authpriv.none;cron.none    /var/log/messages
    
  2. systemd-journald
    新系统使用 journalctl 查看日志:

    journalctl -p err    # 查看错误级别及以上日志
    journalctl -u nginx  # 查看某个服务日志
    journalctl -f        # 实时跟踪日志
    
  3. 日志轮转
    工具:logrotate
    配置:/etc/logrotate.conf/etc/logrotate.d/
    用于日志切割、压缩、删除旧日志。