linux基础————rsyslog日志 管理 自动打包删除日志

系统日志分类 centos7.8

 -/var/log/maillog   默认邮件为异步 好处 减少磁盘io 坏处 由于存储在内存中很容易丢失

 

自定义开机启动日志   local0------6 最多定义7条

例如自定义 ssh日志

vim +37 /etc/ssh/sshd_config

#SyslogFacility AUTHPRIV    这之下插入下面内容保存  
SyslogFacility local6

echo local6.* /var/log/sshd.log  >/etc/rsyslog.d/sshd.conf  #新建系统日志规则

systemctl restart sshd rsyslog     #重启以上 2个服务使之生效

[root@sre ~]# tail -f /var/log/sshd.log
Feb 10 15:10:21 sre sshd[5513]: Server listening on 0.0.0.0 port 22.
Feb 10 15:10:21 sre sshd[5513]: Server listening on :: port 22.
Feb 10 15:13:33 sre sshd[5903]: Accepted password for root from 172.31.7.202 port 47880 ssh2

以上可见日志生成地方已更改

 网络日志生成

CentOS 8 启用网络日志功能
[root@centos8 ~]#vim /etc/rsyslog.conf
## MODULES ####
...省略...
# Provides UDP syslog reception
# for parameters see http://www.rsyslog.com/doc/imudp.html
module(load="imudp") # needs to be done just once
input(type="imudp" port="514")
# Provides TCP syslog reception
# for parameters see http://www.rsyslog.com/doc/imtcp.html
module(load="imtcp") # needs to be done just once
input(type="imtcp" port="514")
#在客户端指定将日志发送到远程的TCP、UDP的日志服务器
[root@centos7 ~]#vim /etc/rsyslog.d/network_log.conf  #network_log 可以随便任意名称 .conf结尾
*.info               @10.0.0.18:514   #UDP    @@10.0.0.18:514    是TCP
CentOS 7 和6 启用网络日志功能
vim /etc/rsyslog.conf
####MODULES####
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514
# Provides TCP syslog reception
$ModLoad imtcp
$InputTCPServerRun 514

  systemctl restart rsyslog  #配置完成后重启

logger -p notice "i am  notice message on this pc"  #快速生成测试日志

找到登录失败的日志

[root@centos8 ~]#awk '/Failed password/{print $(NF-3)}' /var/log/secure 192.168.39.7 192.168.39.18 192.168.39.18

 #lastb -f btmp-test1 | awk '{print $3}'|sort | uniq -c|sort - nr|head  

8374 112.64.33.38  

7041 221.125.235.4  

6502 183.247.184.220

。。。。

日志管理工具 journalctl

#查看所有日志(默认情况下 ,只保存本次启动的日志)
 journalctl
#查看内核日志(不显示应用日志)
 journalctl -k
#查看系统本次启动的日志
 journalctl -b
 journalctl -b -0
#查看上一次启动的日志(需更改设置)
 journalctl -b -1
#查看指定时间的日志
 journalctl --since="2017-10-30 18:10:30"
 journalctl --since "20 min ago"
 journalctl --since yesterday
 journalctl --since "2017-01-10" --until "2017-01-11 03:00"
 journalctl --since 09:00 --until "1 hour ago"
#显示尾部的最新10行日志
 journalctl -n
#显示尾部指定行数的日志
 journalctl -n 20
#实时滚动显示最新日志
 journalctl -f
#查看指定服务的日志
 journalctl /usr/lib/systemd/systemd
#查看指定进程的日志
 journalctl _PID=1
#查看某个路径的脚本的日志
 journalctl /usr/bin/bash
#查看指定用户的日志
2 实战案例:利用 MySQL 存储日志信息
2.1 目标
利用rsyslog日志服务,将收集的日志记录于MySQL中
2.2 环境准备
 journalctl _UID=33 --since today
#查看某个 Unit 的日志
 journalctl -u nginx.service
 journalctl -u nginx.service --since today
#实时滚动显示某个 Unit 的最新日志
 journalctl -u nginx.service -f
#合并显示多个 Unit 的日志
 journalctl -u nginx.service -u php-fpm.service --since today
#查看指定优先级(及其以上级别)的日志,共有8级
0: emerg
1: alert
2: crit
3: err
4: warning
5: notice
6: info
7: debug
 journalctl -p err -b
#日志默认分页输出,--no-pager 改为正常的标准输出
 journalctl --no-pager
#日志管理journalctl
#以 JSON 格式(单行)输出
 journalctl -b -u nginx.service -o json
#以 JSON 格式(多行)输出,可读性更好
 journalctl -b -u nginx.service -o json-pretty
#显示日志占据的硬盘空间
 journalctl --disk-usage
#指定日志文件占据的最大空间
 journalctl --vacuum-size=1G
#指定日志文件保存多久
 journalctl --vacuum-time=1years

在rsyslog服务器上安装连接mysql模块相关的程序包

[root@centos8 ~]#yum install rsyslog-mysql

#在MySQL数据库服务器上创建相关数据库和表,并授权rsyslog能连接至当前服务器 安装mysql8.0版本
 

[root@centos8 ~]#yum install mysql-server

[root@centos8 ~]#mysql -u mysql>source /data/mysql-createDB.sql mysql>CREATE USER  'rsyslog'@'10.0.0.%' IDENTIFIED BY 'magedu'; mysql>GRANT ALL ON Syslog.* TO 'rsyslog'@'10.0.0.%' ;
ssh 172.31.7.204 mysql < /usr/share/doc/rsyslog/mysql-createDB.sql  #将sql脚本复制到数据库服库上

 

[root@mysql ~]#  mysql
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| Syslog             |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
mysql> use Syslog;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------------+
| Tables_in_Syslog       |
+------------------------+
| SystemEvents           |
| SystemEventsProperties |
+------------------------+
2 rows in set (0.00 sec)
mysql> CREATE USER  'rsyslog'@'172.31.7.%' IDENTIFIED BY 'zjx';
Query OK, 0 rows affected (0.01 sec)
mysql> GRANT ALL ON Syslog.* TO 'rsyslog'@'172.31.7.%' ;
Query OK, 0 rows affected (0.00 sec)

 配置日志服务器将日志发送至指定数据库

[root@sre ~]# cat /etc/rsyslog.d/mysql.conf
*.info :ommysql:172.31.7.204,Syslog,rsyslog,zjx
##facility.priority   :ommysql:DBHOST,DBNAME,DBUSER, PASSWORD

#配置rsyslog将日志保存到mysql中
[root@centos8 ~]#vim /etc/rsyslog.conf
#
####MODULES####
#在 MODULES 语言下面,如果是 CentOS 8 加下面行
module(load="ommysql")
#在 MODULES 语言下面,如果是 CentOS 7,6 加下面行
$ModLoad ommysql 


systemctl restart rsyslog.service 

检查是否成功

mysql> SELECT * FROM SystemEvents\G;
*************************** 1. row ***************************
                ID: 1
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: Stopping System Logging Service...
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 2. row ***************************
                ID: 2
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 5
          Priority: 6
          FromHost: sre
           Message: [origin software="rsyslogd" swVersion="8.2102.0-10.el8" x-pid="35734" x-info="https://www.rsyslog.com"] exiting on signal 15.
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: rsyslogd[35734]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 3. row ***************************
                ID: 3
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: rsyslog.service: Succeeded.
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 4. row ***************************
                ID: 4
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: Stopped System Logging Service.
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 5. row ***************************
                ID: 5
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: Starting System Logging Service...
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 6. row ***************************
                ID: 6
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 5
          Priority: 6
          FromHost: sre
           Message: [origin software="rsyslogd" swVersion="8.2102.0-10.el8" x-pid="36200" x-info="https://www.rsyslog.com"] start
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: rsyslogd[36200]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 7. row ***************************
                ID: 7
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: Started System Logging Service.
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 8. row ***************************
                ID: 8
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:36
DeviceReportedTime: 2023-02-10 17:35:36
          Facility: 5
          Priority: 5
          FromHost: sre
           Message: imjournal: journal files changed, reloading...  [v8.2102.0-10.el8 try https://www.rsyslog.com/e/0 ]
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: rsyslogd[36200]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 9. row ***************************
                ID: 9
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:35:45
DeviceReportedTime: 2023-02-10 17:35:45
          Facility: 1
          Priority: 5
          FromHost: sre
           Message: this is a test log
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: root[36231]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 10. row ***************************
                ID: 10
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:36:01
DeviceReportedTime: 2023-02-10 17:36:01
          Facility: 3
          Priority: 6
          FromHost: sre
           Message: Started Session 63 of user root.
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: systemd[1]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
*************************** 11. row ***************************
                ID: 11
        CustomerID: NULL
        ReceivedAt: 2023-02-10 17:36:01
DeviceReportedTime: 2023-02-10 17:36:01
          Facility: 9
          Priority: 6
          FromHost: sre
           Message: (root) CMD (ntpdate ntp3.aliyun.com  &> /dev/null)
        NTSeverity: NULL
        Importance: NULL
       EventSource: NULL
         EventUser: NULL
     EventCategory: NULL
           EventID: NULL
   EventBinaryData: NULL
      MaxAvailable: NULL
         CurrUsage: NULL
          MinUsage: NULL
          MaxUsage: NULL
        InfoUnitID: 1
         SysLogTag: CROND[36271]:
      EventLogType: NULL
   GenericFileName: NULL
          SystemID: NULL
或者 mysql> SELECT COUNT(*) FROM SystemEvents;
+----------+
| COUNT(*) |
+----------+
|       16 |
+----------+
1 row in set (0.05 sec)

Logrotate 日志转储

Logrotate 介绍

logrotate 程序是一个日志文件管理工具。用来把旧的日志文件删除,并创建新的日志文件,称为日志 转储或滚动。可以根据日志文件的大小,也可以根据其天数来转储,这个过程一般通过 cron 程序来执行

Logroate 配置

以设置nginx的日志转储为例

yum -y install nginx 

yum -y install lsof #查看谁在用这个文件

配置参数 说明
配置文件主要参数如下:
配置参数 说明
compress 通过gzip压缩转储以后的日志
nocompress 不压缩
copytruncate 用于还在打开中的日志文件,把当前日志备份并截断
nocopytruncate 备份日志文件但是不截断
create mode owner
group
转储文件,使用指定的权限,所有者,所属组创建新的日志文件
nocreate 不建立新的日志文件
delaycompress 和 compress 一起使用时,转储的日志文件到下一次转储时才压缩
nodelaycompress 覆盖 delaycompress 选项,转储同时压缩
errors address 专储时的错误信息发送到指定的Email 地址
ifempty 即使是空文件也转储,此为默认选项
notifempty 如果是空文件的话,不转储
mail address 把转储的日志文件发送到指定的E-mail 地址
nomail 转储时不发送日志文件
olddir directory 转储后的日志文件放入指定目录,必须和当前日志文件在同一个文件
系统
noolddir 转储后的日志文件和当前日志文件放在同一个目录下
prerotate/endscript 在转储以前需要执行的命令,这两个关键字必须单独成行
postrotate/endscript 在转储以后需要执行的命令,这两个关键字必须单独成行
daily 指定转储周期为每天
weekly 指定转储周期为每周
monthly 指定转储周期为每月
rotate count 指定日志文件删除之前转储的次数,0 指没有备份,5 指保留5 个备份
tabooext [+] list 让logrotate不转储指定扩展名的文件,缺省的扩展名是:.rpm-orig,
.rpmsave, v, 和 ~
size size 当日志文件到达指定的大小时才转储,bytes(缺省)及KB或MB
sharedscripts
默认,对每个转储日志运行prerotate和postrotate脚本,日志文件
的绝对路径作为第一个参数传递给脚本。 这意味着单个脚本可以针对
与多个文件匹配的日志文件条目多次运行(例如/ var / log / news /
*.example)。 如果指定此项sharedscripts,则无论有多少个日志
与通配符模式匹配,脚本都只会运行一次
nosharedscripts 针对每一个转储的日志文件,都执行一次prerotate 和 postrotate脚
本,此为默认值
配置参数 说明
missingok 如果日志不存在,不提示错误,继续处理下一个
nomissingok 如果日志不存在,提示错误,此为默认值

 

范例: 设置nginx的日志转储
范例:对指定日志手动执行日志转储
#生成测试日志
[root@centos8 ~]#dd if=/dev/zero of=/var/log/test1.log bs=2M count=1
1+0 records in
1+0 records out
2097152 bytes (2.1 MB, 2.0 MiB) copied, 0.00291879 s, 719 MB/s
[root@centos8 ~]#dd if=/dev/zero of=/var/log/test2.log bs=2M count=1
1+0 records in
1+0 records out
2097152 bytes (2.1 MB, 2.0 MiB) copied, 0.00200561 s, 1.0 GB/s
#针对不同的日志创建转储配置文件
[root@sre ~]# cat  /etc/logrotate.d/nginx
/apps/nginx/logs/*.log {
    daily
    rotate 10
    missingok
    notifempty
    compress
    delaycompress
    create 644 nginx nginx
    postrotate
      if [ -f /apps/nginx/logs/nginx.pid ]; then
          kill -USR1 `cat /apps/nginx/logs/nginx.pid`
      fi
    endscript
}



[root@centos8 ~]#cat  > /etc/logrotate.d/test1 <<EOF
/var/log/test1.log {
   daily
   rotate 5
   compress
   delaycompress
   missingok
   size 1M
   notifempty
   create 640 bin nobody
   postrotate
 echo `date +%F_%T` >> /data/test1.log
   endscript
}
EOF
[root@centos8 ~]#cat > /etc/logrotate.d/test2 <<EOF
/var/log/test2.log {
   daily
   rotate 5
   compress
   delaycompress
   missingok
   size 1M
   notifempty
   create 644 root root
   postrotate
 echo `date +%F_%T` >> /data/test2.log
   endscript
}
EOF
#针对一个测试日志,手动执行日志转储
[root@sre ~]# logrotate /etc/logrotate.d/test1
[root@sre ~]# ll /var/log/test*
-rw-r----- 1 bin  nobody       0 2月  10 19:44 /var/log/test1.log
-rw-r--r-- 1 root root   2097152 2月  10 19:37 /var/log/test1.log.1
-rw-r--r-- 1 root root   2097152 2月  10 19:38 /var/log/test2.log

[root@sre ~]# dd if=/dev/zero of=/var/log/test1.log bs=6M count=1
记录了1+0 的读入
记录了1+0 的写出
6291456 bytes (6.3 MB, 6.0 MiB) copied, 0.00292703 s, 2.1 GB/s
[root@sre ~]# ll /var/log/test*
-rw-r----- 1 bin  nobody 6291456 2月  10 20:02 /var/log/test1.log
-rw-r--r-- 1 root root   2097152 2月  10 19:37 /var/log/test1.log.1
-rw-r----- 1 bin  nobody 5242880 2月  10 19:57 /var/log/test1.log-20230210
-rw-r--r-- 1 root root         0 2月  10 19:58 /var/log/test2.log
-rw-r--r-- 1 root root   2097152 2月  10 19:38 /var/log/test2.log-20230210
[root@sre ~]# logrotate /etc/logrotate.conf
error: destination /var/log/test1.log-20230210 already exists, skipping rotation
[root@sre ~]# ll /var/log/test*
-rw-r----- 1 bin  nobody 6291456 2月  10 20:02 /var/log/test1.log
-rw-r--r-- 1 root root   2097152 2月  10 19:37 /var/log/test1.log.1
-rw-r----- 1 bin  nobody    5115 2月  10 19:57 /var/log/test1.log-20230210.gz
-rw-r--r-- 1 root root         0 2月  10 19:58 /var/log/test2.log
-rw-r--r-- 1 root root   2097152 2月  10 19:38 /var/log/test2.log-20230210


出现以上情况既完成配置

删除 除最近10个日志以外的日志

ls /apps/nginx/logs/access_json.log-* -t | tail -n  -9 |xargs rm -f

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值