haproxy配置技巧

ubuntu22.04下haproxy的日志记录到rsyslog配置方法

ubuntu22.04 用apt install haproxy 进行安装后,/etc/haproxy/haproxy.cfg的配置中包含的日志选项:

global
        log /dev/log    local0
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

其中 log /dev/log local0 的意思就是haproxy日志进入到本地日志系统中 (/dev/log).
log: 全局的日志配置,local0是日志设备,info 表示日志级别。其中日志级别有 err、warning、info、debug 四种可选。这个配置表示使用 127.0.0.1 上的 rsyslog 服务中的 local0 日志设备,记录日志等级为 info;log 指定收集哪个机器的 log,log 的收集是通过系统工具来实现的,在 centos6 版本之前以 syslog 来收集日志,6版本变为了 rsysylog。这些都是用于收集系统的日志,local0 指定设备,info 表示输出日志的级别,error 级别是在报错的时候才会输出。info 只要有正常信息都会进行输出,生产环境建议设置 为 notice 级别。

安装rsyslog系统,apt install rsyslog,并启动:systemctl start rsyslog, 查看状态: systemctl status rsyslog ,确保没有报错:

#  systemctl status rsyslog
● rsyslog.service - System Logging Service
     Loaded: loaded (/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2024-12-29 04:11:52 UTC; 15min ago
TriggeredBy: ● syslog.socket
       Docs: man:rsyslogd(8)
             man:rsyslog.conf(5)
             https://www.rsyslog.com/doc/
   Main PID: 4555 (rsyslogd)
      Tasks: 4 (limit: 1051)
     Memory: 1.1M
        CPU: 11ms
     CGroup: /system.slice/rsyslog.service
             └─4555 /usr/sbin/rsyslogd -n -iNONE

编辑 /etc/rsyslog.conf 这个配置文件,在最后加两行:

# Log HAProxy messages to /var/log/haproxy.log
local0.*    /var/log/haproxy.log
local1.*    /var/log/haproxy.log

重启服务: systemctl restart rsyslog

先确保日志文件的权限正确:

ls -l /var/log/haproxy.log
-rw-r----- 1 syslog adm 46383 Dec 29 04:19 /var/log/haproxy.log

如果权限不对,要进行调整:

sudo chown syslog:adm /var/log/haproxy.log
sudo chmod 640 /var/log/haproxy.log

一般情况下,日志已经进来了:tail -f /var/log/haproxy.log , 如果没有进来,可以进行排错:

logger -p local0.info "Test message for HAProxy logging"
logger -p local1.notice "Test message for HAProxy notice"

通过 tail -f /var/log/haproxy.log 进行查看。

更进一步,代理多个域名,必须要记录每个域名的日志,则在配置文件中添加:

frontend http_frontend
............
    capture request header Host len 20
    capture request header Referer len 60
    http-request capture req.hdr(Host) len 10
    http-request capture req.hdr(User-Agent) len 100
    # 下面是官方标准的http日志格式
    log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"
............

可以看到,先capture到header,然后log-format输出。

更详细的官方说明文档:
https://www.haproxy.com/blog/haproxy-log-customization
https://www.haproxy.com/blog/introduction-to-haproxy-logging

Dec 30 11:00:53 unique-poll-1 haproxy[6820]: 110.249.202.147:52390 [30/Dec/2024:11:00:53.662] http_frontend~ http_servers/http_server1 0/0/0/1/1 404 272 - - ---- 6/6/0/0/0 0/0 {moneyslow.com||moneyslow.co|like Gecko) Mobile Safari/537.36 (compatible; Bytespider; https://zhanzhang.toutiao.com/)} "GET https://moneyslow.com/top/32927.htm HTTP/2.0"