天天看點

FileBeat筆記(一)——安裝和采集Springboot日志

1. 下載下傳和安裝

# windows 下載下傳,本文以windows指令示範
https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.6.2-windows-x86_64.zip

# linux 下載下傳
wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.6.2-darwin-x86_64.tar.gz

           

1.1. 配置filebeat.yml

完整的配置放在文章末尾

1.2. ES模闆fields.yml

直連ES時可以自動導模闆,否則需要手動導入

# 手動導入
.\filebeat.exe setup --template -E output.logstash.enabled=false -E 'output.elasticsearch.hosts=["localhost:9200"]'
# 删除舊的模闆文檔
curl -XDELETE 'http://localhost:9200/filebeat-*'

           

1.3. 設定kibana儀表盤

# 初次使用可以跳過此步,可以熟悉了之後再配置Kibana
.\filebeat.exe setup --dashboards
           

1.4. 為Logstash輸出設定儀表闆

# 初次使用可以跳過此步,可以熟悉了之後再配置Kibana
.\filebeat.exe setup -e `
  -E output.logstash.enabled=false `
  -E output.elasticsearch.hosts=['140.143.206.106:9200'] `
  -E output.elasticsearch.username=filebeat_internal `
  -E output.elasticsearch.password=YOUR_PASSWORD `
  -E setup.kibana.host=localhost:5601
           

2. 啟動

2.1. 安裝

如果是windows上, 可以修改一下install-service-filebeat.ps1裡的安裝路徑(E:\filebeat-6.6.2-windows-x86_64)

# Delete and stop the service if it already exists.
if (Get-Service filebeat -ErrorAction SilentlyContinue) {
  $service = Get-WmiObject -Class Win32_Service -Filter "name='filebeat'"
  $service.StopService()
  Start-Sleep -s 1
  $service.delete()
}

$workdir = Split-Path $MyInvocation.MyCommand.Path

# Create the new service.
New-Service -name filebeat `
  -displayName Filebeat `
  -binaryPathName "`"$workdir\filebeat.exe`" -c `"$workdir\filebeat.yml`" -path.home `"$workdir`" -path.data `"E:\filebeat-6.6.2-windows-x86_64\datas`" -path.logs `"E:\filebeat-6.6.2-windows-x86_64\logs`""

           

2.2. 啟動

# mac and linux 執行:
sudo chown root filebeat.yml 
sudo ./filebeat -e
sudo ./filebeat -e -c filebeat.yml -d "publish"

# windows 以管理者身份執行,記得修改ps1裡的路徑
# 安裝,沒有報錯則成功
PS E:\filebeat-6.6.2-windows-x86_64> .\install-service-filebeat.ps1

# 解除安裝
PS E:\filebeat-6.6.2-windows-x86_64> .\uninstall-service-filebeat.ps1

# 啟動
PS E:\filebeat-6.6.2-windows-x86_64> Start-Service filebeat

           

啟動成功後可以檢視日志,看是否正常采集

測試階段,采集的日志偏移量存在filebeat系統資料庫中,删除datas目錄下的registry相關檔案後,可以從頭再次采集

3. 配置多行采集

3.1. multiline在Filebeat中的配置實作(第一種方式,推薦):

filebeat.prospectors:
    -
       paths:
          - /home/project/elk/logs/test.log
       input_type: log 
       multiline:
            pattern: '^\['
            negate: true
            match: after
output:
   logstash:
      hosts: ["localhost:5044"]
           

pattern:正規表達式

negate:預設為false,表示比對pattern的行合并到上一行;true表示不比對pattern的行合并到上一行

match:after表示合并到上一行的末尾,before表示合并到上一行的行首

# 該配置表示将不比對pattern模式的行合并到上一行的末尾
pattern: '\['
negate: true
match: after
           

3.2. multiline在Logstash中的配置實作方式(第二種方式)

input {
  beats {
    port => 5044
  }
}

filter {
  multiline {
    pattern => "%{LOGLEVEL}\s*\]"
    negate => true
    what => "previous"
  }
}

output {
  elasticsearch {
    hosts => "localhost:9200"
  }
}
           

(1)Logstash中配置的what屬性值為previous,相當于Filebeat中的after,Logstash中配置的what屬性值為next,相當于Filebeat中的before。

(2)pattern => “%{LOGLEVEL}\s*]” 中的LOGLEVEL是Logstash預制的正則比對模式,預制的還有好多常用的正則比對模式,詳細請看:https://github.com/logstash-plugins/logstash-patterns-core/tree/master/patterns

3.3. 日志的時間字段替換為日志資訊中的時間

https://juejin.im/entry/5a2761446fb9a045186a9b36

3.4. 辨別不同系統子產品的字段或根據不同子產品建ES索引

fileBeat 通過新增:log_from字段來辨別不同的系統子產品日志
filebeat.prospectors:
    -
       paths:
          - /home/project/elk/logs/account.log
       input_type: log 
       multiline:
            pattern: '^\['
            negate: true
            match: after
       fields: # 新增log_from字段
         log_from: account

    -
       paths:
          - /home/project/elk/logs/customer.log
       input_type: log 
       multiline:
            pattern: '^\['
            negate: true
            match: after
       fields:
         log_from: customer
output:
   logstash:
      hosts: ["localhost:5044"]
           

然後修改Logstash中output的配置内容,

在output中增加index屬性,%{type}表示按不同的document_type值建ES索引:

output {
  elasticsearch {
    hosts => "localhost:9200"
    index => "%{type}"
  }
}
           

以下是完整的測試配置,注意修改日志路徑:

###################### Filebeat Configuration Example #########################

# This file is an example configuration file highlighting only the most common
# options. The filebeat.reference.yml file from the same directory contains all the
# supported options with more comments. You can use it as a reference.
#
# You can find the full configuration reference here:
# https://www.elastic.co/guide/en/beats/filebeat/index.html

# For more available modules and options, please see the filebeat.reference.yml sample
# configuration file.

#=========================== Filebeat inputs =============================

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

- type: log

  # Change to true to enable this input configuration.
  enabled: true

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - D:\IDEA\infrastructure\logs\*\*.log
    #- /var/log/*.log
    #- c:\programdata\elasticsearch\logs\*

  # Exclude lines. A list of regular expressions to match. It drops the lines that are
  # matching any regular expression from the list.
  #exclude_lines: ['^DBG']

  # Include lines. A list of regular expressions to match. It exports the lines that are
  # matching any regular expression from the list.
  #include_lines: ['^ERR', '^WARN']

  # Exclude files. A list of regular expressions to match. Filebeat drops the files that
  # are matching any regular expression from the list. By default, no files are dropped.
  #exclude_files: ['.gz$']

  # Optional additional fields. These fields can be freely picked
  # to add additional information to the crawled log files for filtering
  #fields:
  #  level: debug
  #  review: 1

  ### Multiline options
  multiline:
    pattern: '^\['
    negate: true
    match: after
  # Multiline can be used for log messages spanning multiple lines. This is common
  # for Java Stack Traces or C-Line Continuation

  # The regexp Pattern that has to be matched. The example pattern matches all lines starting with [
  #multiline.pattern: ^\[

  # Defines if the pattern set under pattern should be negated or not. Default is false.
  #multiline.negate: false

  # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern
  # that was (not) matched before or after or as long as a pattern is not matched based on negate.
  # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash
  #multiline.match: after
  fields: 
    log_from: api-gateway-application

#============================= Filebeat modules ===============================

filebeat.config.modules:
  # Glob pattern for configuration loading
  path: ${path.config}/modules.d/*.yml

  # Set to true to enable config reloading
  reload.enabled: false

  # Period on which files under path should be checked for changes
  #reload.period: 10s

#==================== Elasticsearch template setting ==========================

setup.template.settings:
  index.number_of_shards: 3
  #index.codec: best_compression
  #_source.enabled: false

#================================ General =====================================

# The name of the shipper that publishes the network data. It can be used to group
# all the transactions sent by a single shipper in the web interface.
#name:

# The tags of the shipper are included in their own field with each
# transaction published.
#tags: ["service-X", "web-tier"]

# Optional fields that you can specify to add additional information to the
# output.
#fields:
#  env: staging


#============================== Dashboards =====================================
# These settings control loading the sample dashboards to the Kibana index. Loading
# the dashboards is disabled by default and can be enabled either by setting the
# options here, or by using the `-setup` CLI flag or the `setup` command.
#setup.dashboards.enabled: false

# The URL from where to download the dashboards archive. By default this URL
# has a value which is computed based on the Beat name and version. For released
# versions, this URL points to the dashboard archive on the artifacts.elastic.co
# website.
#setup.dashboards.url:

#============================== Kibana =====================================

# Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.
# This requires a Kibana endpoint configuration.
setup.kibana:

  # Kibana Host
  # Scheme and port can be left out and will be set to the default (http and 5601)
  # In case you specify and additional path, the scheme is required: http://localhost:5601/path
  # IPv6 addresses should always be defined as: https://[2001:db8::1]:5601
  host: "localhost:5601"

  # Kibana Space ID
  # ID of the Kibana Space into which the dashboards should be loaded. By default,
  # the Default Space will be used.
  #space.id:

#============================= Elastic Cloud ==================================

# These settings simplify using filebeat with the Elastic Cloud (https://cloud.elastic.co/).

# The cloud.id setting overwrites the `output.elasticsearch.hosts` and
# `setup.kibana.host` options.
# You can find the `cloud.id` in the Elastic Cloud web UI.
#cloud.id:

# The cloud.auth setting overwrites the `output.elasticsearch.username` and
# `output.elasticsearch.password` settings. The format is `<user>:<pass>`.
#cloud.auth:

#================================ Outputs =====================================

# Configure what output to use when sending the data collected by the beat.

#-------------------------- Elasticsearch output ------------------------------
#output.elasticsearch:
  # Array of hosts to connect to.
  #hosts: ["140.143.206.106:9200"]

  # Enabled ilm (beta) to use index lifecycle management instead daily indices.
  #ilm.enabled: false

  # Optional protocol and basic auth credentials.
  #protocol: "https"
  #username: "elastic"
  #password: "changeme"

#----------------------------- Logstash output --------------------------------
output.logstash:
  # The Logstash hosts
  hosts: ["localhost:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

#================================ Processors =====================================

# Configure processors to enhance or manipulate events generated by the beat.

processors:
  - add_host_metadata: ~
  - add_cloud_metadata: ~

#================================ Logging =====================================

# Sets log level. The default log level is info.
# Available log levels are: error, warning, info, debug
#logging.level: debug

# At debug level, you can selectively enable logging only for some components.
# To enable all selectors use ["*"]. Examples of other selectors are "beat",
# "publish", "service".
#logging.selectors: ["*"]

#============================== Xpack Monitoring ===============================
# filebeat can export internal metrics to a central Elasticsearch monitoring
# cluster.  This requires xpack monitoring to be enabled in Elasticsearch.  The
# reporting is disabled by default.

# Set to true to enable the monitoring reporter.
#xpack.monitoring.enabled: false

# Uncomment to send the metrics to Elasticsearch. Most settings from the
# Elasticsearch output are accepted here as well. Any setting that is not set is
# automatically inherited from the Elasticsearch output configuration, so if you
# have the Elasticsearch output configured, you can simply uncomment the
# following line.
#xpack.monitoring.elasticsearch:

           

繼續閱讀