linux日志管理
官网 : https://www.rsyslog.com/
rsyslog 特性
- 多线程
- UDP, TCP, SSL, TLS, RELP
- MySQL, PGSQL, Oracle实现日志存储
- 强大的过滤器,可实现过滤记录日志信息中任意部分
- 自定义输出格式
- 适用于企业级中继链
- 多线程
- UDP, TCP, SSL, TLS, RELP
- MySQL, PGSQL, Oracle实现日志存储
- 强大的过滤器,可实现过滤记录日志信息中任意部分
- 自定义输出格式
- 适用于企业级中继链
- 多线程
- UDP, TCP, SSL, TLS, RELP
- MySQL, PGSQL, Oracle实现日志存储
- 强大的过滤器,可实现过滤记录日志信息中任意部分
- 自定义输出格式
- 适用于企业级中继链
rsyslog 管理
- facility:设施,从功能或程序上对日志进行归类
#内置分类
auth, authpriv, cron, daemon,ftp,kern, lpr, mail, news, security(auth),user(default), uucp, syslog
#自定义的分类
local0-local7
- Priority 优先级别,从低到高排序
debug,info, notice, warn(warning), err(error), crit(critical), alert,emerg(panic)
- help
[root@Rocky8 ~]#rpm -q rsyslog
rsyslog-8.2102.0-7.el8_6.1.x86_64
[root@ubuntu2204 ~]#dpkg -l rsyslog
期望状态=未知(u)/安装(i)/删除(r)/清除(p)/保持(h)
| 状态=未安装(n)/已安装(i)/仅存配置(c)/仅解压缩(U)/配置失败(F)/不完全安装(H)/触发器等待(W)/触发器未决(T)
|/ 错误?=(无)/须重装(R) (状态,错误:大写=故障)
||/ 名称 版本 体系结构 描述
+++-==============-===================-============-=========================================
ii rsyslog 8.2112.0-2ubuntu2.2 amd64 reliable system and kernel logging daemon
rsyslog 相关文件
- 程序包:rsyslog
- 主程序:/usr/sbin/rsyslogd
- CentOS 6:/etc/rc.d/init.d/rsyslog {start|stop|restart|status}
- CentOS 7,8:/usr/lib/systemd/system/rsyslog.service
- 配置文件:/etc/rsyslog.conf,/etc/rsyslog.d/*.conf
- 库文件: /lib64/rsyslog/*.so
[root@ubuntu2204 ~]#cat /lib/systemd/system/rsyslog.service
[Unit]
Description=System Logging Service
Requires=syslog.socket
Documentation=man:rsyslogd(8)
Documentation=man:rsyslog.conf(5)
Documentation=https://www.rsyslog.com/doc/
[Service]
Type=notify
ExecStart=/usr/sbin/rsyslogd -n -iNONE
StandardOutput=null
Restart=on-failure
# Increase the default a bit in order to allow many simultaneous
# files to be monitored, we might need a lot of fds.
LimitNOFILE=16384
[Install]
WantedBy=multi-user.target
Alias=syslog.service
[root@ubuntu2204 ~]# ps aux|grep rsyslogd
syslog 2567 0.0 0.3 222404 6140 ? Ssl 20:22 0:00 /usr/sbin/rsyslogd -n -iNONE
root 2627 0.0 0.1 9232 2336 pts/0 S+ 20:33 0:00 grep --color=auto rsyslogd
默认日志配置
# redheat
[root@Rocky8 ~]#cat /etc/rsyslog.conf
# rsyslog configuration file
# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# or latest version online at http://www.rsyslog.com/doc/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html
#### MODULES ####
module(load="imuxsock" # provides support for local system logging (e.g. via logger command)
SysSock.Use="off") # Turn off message reception via local log socket;
# local messages are retrieved through imjournal now.
module(load="imjournal" # provides access to the systemd journal
StateFile="imjournal.state") # File to store the position in the journal
#module(load="imklog") # reads kernel messages (the same are read from journald)
#module(load="immark") # provides --MARK-- message capability
# 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")
#### GLOBAL DIRECTIVES ####
# Where to place auxiliary files
global(workDirectory="/var/lib/rsyslog")
# Use default timestamp format
module(load="builtin:omfile" Template="RSYSLOG_TraditionalFileFormat")
# Include all config files in /etc/rsyslog.d/
include(file="/etc/rsyslog.d/*.conf" mode="optional")
#### RULES ####
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* -/var/log/maillog
# Log cron stuff
cron.* /var/log/cron
# Everybody gets emergency messages
*.emerg :omusrmsg:*
# Save news errors of level crit and higher in a special file.
uucp,news.crit /var/log/spooler
# Save boot messages also to boot.log
local7.* /var/log/boot.log
# ### sample forwarding rule ###
#action(type="omfwd"
# An on-disk queue is created for this action. If the remote host is
# down, messages are spooled to disk and sent when it is up again.
#queue.filename="fwdRule1" # unique name prefix for spool files
#queue.maxdiskspace="1g" # 1gb space limit (use as much as possible)
#queue.saveonshutdown="on" # save messages to disk on shutdown
#queue.type="LinkedList" # run asynchronously
#action.resumeRetryCount="-1" # infinite retries if host is down
# Remote Logging (we use TCP for reliable delivery)
# remote_host is: name/ip, e.g. 192.168.0.1, port optional e.g. 10514
#Target="remote_host" Port="XXX" Protocol="tcp")
------------------------------------------------------------------------------------
# ubuntu
[root@ubuntu2204 ~]#cat /etc/rsyslog.d/50-default.conf
# Default rules for rsyslog.
#
# For more information see rsyslog.conf(5) and /etc/rsyslog.conf
#
# First some standard log files. Log by facility.
#
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
#cron.* /var/log/cron.log
#daemon.* -/var/log/daemon.log
kern.* -/var/log/kern.log
#lpr.* -/var/log/lpr.log
mail.* -/var/log/mail.log
#user.* -/var/log/user.log
#
# Logging for the mail system. Split it up so that
# it is easy to write scripts to parse these files.
#
#mail.info -/var/log/mail.info
#mail.warn -/var/log/mail.warn
mail.err /var/log/mail.err
#
# Some "catch-all" log files.
#
#*.=debug;\
# auth,authpriv.none;\
# news.none;mail.none -/var/log/debug
#*.=info;*.=notice;*.=warn;\
# auth,authpriv.none;\
# cron,daemon.none;\
# mail,news.none -/var/log/messages
#
# Emergencies are sent to everybody logged in.
#
*.emerg :omusrmsg:*
#
# I like to have messages displayed on the console, but only on a virtual
# console I usually leave idle.
#
#daemon,mail.*;\
# news.=crit;news.=err;news.=notice;\
# *.=debug;*.=info;\
# *.=notice;*.=warn /dev/tty8
常见日志文件
/var/log/secure,/var/log/auth.log:系统安全日志,文本格式,应周期性分析 /var/log/btmp:当前系统上,用户的失败尝试登录相关的日志信息,二进制格式,lastb命令进行查看 /var/log/wtmp:当前系统上,用户正常登录系统的相关日志信息,二进制格式,last命令可以查看
#显示系统关机项和运行级别更改
last -x, --system
/var/log/lastlog:每一个用户最近一次的登录信息,二进制格式,lastlog命令可以查看 /var/log/dmesg:CentOS7 之前版本系统引导过程中的日志信息,文本格式,开机后的硬件变化将不再记录,也可以通过专用命令 dmesg查看,可持续记录硬件变化的情况 /var/log/boot.log 系统服务启动的相关信息,文本格式,Ubuntu无此文件 /var/log/messages(红帽系统),/var/log/syslog (Ubuntu) :系统中大部分的信息 /var/log/anaconda : anaconda的日志,Ubuntu无此文件
journalctl系统自带的Unit日志管理工具
/etc/systemd/journald.conf
#用法
#查看所有日志(默认情况下 ,只保存本次启动的日志)
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
#查看指定用户的日志
journalctl _UID=33 --since today
#查看某个 Unit 的日志
journalctl -u nginx.service
#实时滚动显示某个 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
配置网络日志服务同时转存至mysql
#配置日志服务器
#安装rsyslog-mysql
105 2022-11-19 10:36:48 apt install -y rsyslog-mysql
#查看包rsyslog-mysql内容,找到里面带的表创建语句
106 2022-11-19 10:38:07 dpkg -L rsyslog-mysql
#传给数据库服务器创建表
109 2022-11-19 10:44:03 scp /usr/share/dbconfig-common/data/rsyslog-mysql/install/mysql 10.0.0.8:
[root@ubuntu2204 ~]#vim /etc/rsyslog.conf --> 开启日志转存端口,启用mysql日志存储插件
#################
#### MODULES ####
#################
module(load="imuxsock") # provides support for local system logging
#module(load="immark") # provides --MARK-- message capability
# provides UDP syslog reception
module(load="imudp")
input(type="imudp" port="514")
# provides TCP syslog reception
module(load="imtcp")
input(type="imtcp" port="514")
module(load="ommysql")
[root@ubuntu2204 ~]#vim /etc/rsyslog.d/50-default.conf --> 配置mysql链接数据
# First some standard log files. Log by facility.
#
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
*.info :ommysql:10.0.0.8,Syslog,rsyslog,123456
[root@ubuntu2204 ~]#cat /etc/rsyslog.d/mysql.conf --> 自动生成链接数据,检查一下
### Configuration file for rsyslog-mysql
### Changes are preserved
module (load="ommysql")
*.* action(type="ommysql" server="10.0.0.8" db="Syslog" uid="rsyslog" pwd="123456")
[root@ubuntu2204 ~]#systemctl restart rsyslog.service
-----------------------------------------------------------------------------------------
#配置数据库服务,创建用户,授权,建库建表
[root@mysql-master ~]#cat mysql
CREATE TABLE IF NOT EXISTS SystemEvents
(
ID int unsigned not null auto_increment primary key,
CustomerID bigint,
ReceivedAt datetime NULL,
DeviceReportedTime datetime NULL,
Facility smallint NULL,
Priority smallint NULL,
FromHost varchar(60) NULL,
Message text,
NTSeverity int NULL,
Importance int NULL,
EventSource varchar(60),
EventUser varchar(60) NULL,
EventCategory int NULL,
EventID int NULL,
EventBinaryData text NULL,
MaxAvailable int NULL,
CurrUsage int NULL,
MinUsage int NULL,
MaxUsage int NULL,
InfoUnitID int NULL ,
SysLogTag varchar(60),
EventLogType varchar(60),
GenericFileName VarChar(60),
SystemID int NULL
);
CREATE TABLE IF NOT EXISTS SystemEventsProperties
(
ID int unsigned not null auto_increment primary key,
SystemEventID int NULL ,
ParamName varchar(255) NULL ,
ParamValue text NULL
);
[root@centos8 ~]#mysql -u
mysql>source /data/mysql-createDB.sql
mysql>CREATE USER 'rsyslog'@'10.0.0.%' IDENTIFIED BY '123456';
mysql>GRANT ALL ON Syslog.* TO 'rsyslog'@'10.0.0.%' ;
----------------------------------------------
#测试
#在日志服务器上生成日志
[root@ubuntu2204 ~]#logger "this is a test log"
#在数据库上查询到上面的测试日志
mysql>SELECT COUNT(*) FROM SystemEvents;
mysql> use Syslog
Database changed
mysql> show tables;
Empty set (0.01 sec)
mysql> source create-rsyslogdb.sql
Query OK, 0 rows affected (0.10 sec)
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+------------------------+
| Tables_in_Syslog |
+------------------------+
| SystemEvents |
| SystemEventsProperties |
+------------------------+
2 rows in set (0.00 sec)
mysql> SELECT COUNT(*) FROM SystemEvents;
+----------+
| COUNT(*) |
+----------+
| 13736 |
+----------+
1 row in set (0.01 sec)
Logrotate-日志的转储
logrotate 程序是一个日志文件管理工具。用来把旧的日志文件删除,并创建新的日志文件,称为日志转 储或滚动。可以根据日志文件的大小,也可以根据其天数来转储,这个过程一般通过 cron 程序来执行。
#相关文件
计划任务:/etc/cron.daily/logrotate
程序文件:/usr/sbin/logrotate
配置文件: /etc/logrotate.conf
日志文件:/var/lib/logrotate/logrotate.status
-------------------------------------------------------------------------------------------
[root@ubuntu2204 ~]#dpkg -l logrotate
期望状态=未知(u)/安装(i)/删除(r)/清除(p)/保持(h)
| 状态=未安装(n)/已安装(i)/仅存配置(c)/仅解压缩(U)/配置失败(F)/不完全安装(H)/触发器等待(W)/触发器未决(T)
|/ 错误?=(无)/须重装(R) (状态,错误:大写=故障)
||/ 名称 版本 体系结构 描述
+++-==============-=================-============-=================================
ii logrotate 3.19.0-1ubuntu1.1 amd64 Log rotation utility
[root@ubuntu2204 ~]#dpkg -L logrotate
/.
/etc
/etc/cron.daily
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/etc/logrotate.d/btmp
/etc/logrotate.d/wtmp
/lib
/lib/systemd
/lib/systemd/system
/lib/systemd/system/logrotate.service
/lib/systemd/system/logrotate.timer
/usr
/usr/sbin
/usr/sbin/logrotate
/usr/share
/usr/share/bug
/usr/share/bug/logrotate
/usr/share/bug/logrotate/script
/usr/share/doc
/usr/share/doc/logrotate
/usr/share/doc/logrotate/NEWS.Debian.gz
/usr/share/doc/logrotate/changelog.Debian.gz
/usr/share/doc/logrotate/copyright
/usr/share/man
/usr/share/man/man5
/usr/share/man/man8
/usr/share/man/man8/logrotate.8.gz
/var
/var/lib
/var/lib/logrotate
/usr/share/man/man5/logrotate.conf.5.gz
[root@Rocky8 ~]#rpm -ql logrotate
/etc/cron.daily
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/etc/logrotate.d/btmp
/etc/logrotate.d/wtmp
/etc/rwtab.d/logrotate
/usr/lib/.build-id
/usr/lib/.build-id/b6
/usr/lib/.build-id/b6/596acebd8053c625902908d26e5ba3655ddaa7
/usr/sbin/logrotate
/usr/share/doc/logrotate
/usr/share/doc/logrotate/ChangeLog.md
/usr/share/licenses/logrotate
/usr/share/licenses/logrotate/COPYING
/usr/share/man/man5/logrotate.conf.5.gz
/usr/share/man/man8/logrotate.8.gz
/var/lib/logrotate
/var/lib/logrotate/logrotate.status
配置参数
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/example/*.log)。 如果指定此项sharedscripts,则无论有多少个日志与
通配符模式匹配,脚本都只会运行一次
nosharedscripts 针对每一个转储的日志文件,都执行一次prerotate 和 postrotate脚本,此为默认值
missingok 如果日志不存在,不提示错误,继续处理下一个
nomissingok 如果日志不存在,提示错误,此为默认值
案例
#nginx安装内置转储规则
[root@ubuntu2204 ~]#cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
prerotate
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
fi \
endscript
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
#Ubuntu22.04 日志转储
[root@ubuntu2204 ~]#mkdir -p /var/log/test /data
[root@ubuntu2204 ~]#ll /var/log/test/*
-rw-r--r-- 1 root root 2097152 11月 18 12:21 /var/log/test/test1.log
[root@ubuntu2204 ~]#dd if=/dev/zero of=/var/log/test/test1.log bs=1M count=2
[root@ubuntu2204 ~]#ll /var/log/test/*
-rw-r--r-- 1 root root 2097152 11月 18 12:21 /var/log/test/test1.log
[root@ubuntu2204 ~]#cat /etc/logrotate.d/test1
/var/log/test/test1.log {
daily
rotate 5
compress
delaycompress
missingok
size 1M
notifempty
create 0640 bin daemon
sharedscripts
postrotate
echo `date +%F_%T` >> /data/test1.log
endscript
}
#手动转储
[root@ubuntu2204 ~]#logrotate /etc/logrotate.d/test1
#查看结果
[root@ubuntu2204 ~]#ll /var/log/test/
总用量 2056
drwxr-xr-x 2 600 root 4096 11月 18 12:22 ./
drwxrwxr-x 12 root syslog 4096 11月 18 12:14 ../
-rw-r----- 1 bin daemon 0 11月 18 12:22 test1.log
-rw-r--r-- 1 root root 2097152 11月 18 12:21 test1.log.1
#添加日志
[root@ubuntu2204 ~]#dd if=/dev/zero of=/var/log/test/test1.log bs=1M count=2
#手动转储
[root@ubuntu2204 ~]#logrotate /etc/logrotate.d/test1
#观察结果,发现延迟压缩
[root@ubuntu2204 ~]#ll /var/log/test/
总用量 2060
drwxr-xr-x 2 600 root 4096 11月 18 12:23 ./
drwxrwxr-x 12 root syslog 4096 11月 18 12:14 ../
-rw-r----- 1 bin daemon 0 11月 18 12:23 test1.log
-rw-r----- 1 bin daemon 2097152 11月 18 12:23 test1.log.1
-rw-r--r-- 1 root root 2067 11月 18 12:21 test1.log.2.gz
[root@ubuntu2204 ~]#cat /data/test1.log
2022-11-18_12:22:40
2022-11-18_12:23:07
我是moore,大家一起加油!