将 Apache 的错误日志发送到 Slack

首先

由于最近开始使用slack,我决定先试着将Apache的错误日志转发过去。大部分按照这里的指南操作是可以的,但也有一些细微的修改,所以我想将这些变动也整理一下,以备忘录之用。

准备好

使用 fluentd 进行日志收集和传输。假设 fluentd 已经安装好,现在需要安装所需的插件。

$ sudo td-agent-gem install fluent-plugin-slack
$ sudo td-agent-gem install fluent-plugin-rewrite-tag-filter
$ sudo td-agent-gem install fluent-plugin-record-reformer

此外,需要root权限才能访问Apache的日志存储在/var/log/apache2中。因此,需要将fluentd的执行用户更改为root。在Ubuntu上,可以打开/etc/init.d/td-agent并从td-agent进行更改(参考)。

# TD_AGENT_USER=td-agent
# TD_AGENT_GROUP=td-agent
TD_AGENT_USER=root
TD_AGENT_GROUP=root

对于CentOS操作系统,需要在/etc/sysconfig/td-agent文件中添加以下内容。

TD_AGENT_USER=root
TD_AGENT_GROUP=root

流畅日志的配置

接下来进行fluentd的配置。所使用的配置如下所示。

####
## Source descriptions:
##

## apache error log.
<source>
  type tail
  format /^\[(?<time>[^\]]*)\] \[(?<level>[^\]]*)\] \[client (?<client>[^\]]*)\] (?<message>.*)$/
  time_format %a %b %d %H:%M:%S %Y
  pos_file /tmp/td-agent/httpd_error_log.pos
  path /var/log/httpd/error_log
  tag httpd.error_log
</source>

####
## Edit descriptions:
##
<match httpd.error_log>
  type rewrite_tag_filter
  rewriterule1 level error slack.${tag}
</match>

<match slack.**>
  type record_reformer
  tag reformed.${tag}
  <record>
    source_id ${tag_suffix[1]}
  </record>
</match>

####
## Output descriptions:
##
<match reformed.slack.**>
  type slack
  webhook_url <slack の設定からコピー>
  channel admin
  username fluentd
  title_keys source_id
  title %s
  color danger
  flush_interval 5s
</match>

我打算在标题中显示来自哪个服务器的错误,最初我想将主机名包含在标签中,然后通过标签构建标题。但是,slack插件似乎不支持标签的占位符,所以我决定在record_reformer插件中添加source_id。

另外,日志和日期的格式因环境不同而有所差异,直接使用捕获的值可能会导致错误。

format /^\[(?<time>[^\]]*)\] \[(?<level>[^\]]*)\] \[client (?<client>[^\]]*)\] (?<message>.*)$/
time_format %a %b %d %H:%M:%S %Y

如果出现错误,请将设置更改为适当的选项。

广告
将在 10 秒后关闭
bannerAds