0Pricing
Elasticsearch & Full Text Search Systems · Урок

Logstash для загрузки данных

Научитесь использовать Logstash для сбора, разбора и преобразования данных из разных источников перед их индексированием в Elasticsearch.

«Logstash для загрузки данных» — бесплатный урок Elasticsearch & Full Text Search Systems на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Elasticsearch & Full Text Search Systems, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Elasticsearch & Full Text Search Systems содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to Logstash

Welcome to Logstash! It's a powerful, open-source data collection engine with real-time pipelining capabilities. It's a key component of the Elastic Stack (ELK stack), alongside Elasticsearch and Kibana.

Think of Logstash as the 'L' in ELK. Its job is to ingest data from various sources, process it, and then send it to a 'stash' (often Elasticsearch) for storage and analysis.

The Logstash Pipeline

Logstash works by processing data through a pipeline. This pipeline consists of three main stages:

  • Input: Where data is collected from its source.
  • Filter: Where data is processed, parsed, and transformed.
  • Output: Where processed data is sent to its destination.

Data flows sequentially from input to filter to output, allowing for flexible and powerful data manipulation.

Input Stage: Collecting Data

The input stage is responsible for collecting data from various sources. Logstash supports a wide array of input plugins, allowing it to connect to almost any data source.

Common input sources include:

  • Files: Reading logs from disk.
  • Beats: Receiving data from lightweight data shippers like Filebeat or Metricbeat.
  • HTTP/TCP/UDP: Listening for network traffic.
  • Databases: Pulling data from relational databases.

Input Example: Reading Files

Here's a simple Logstash configuration snippet using the file input plugin. This tells Logstash to read all .log files from the specified directory.

The type field helps categorize the incoming events, which can be useful later in filters or outputs.

input {
  file {
    path => "/var/log/*.log"
    type => "syslog"
    start_position => "beginning"
  }
}

Filter Stage: Transforming Data

The filter stage is where the magic happens! This is where you parse, modify, and enrich your raw data before it's sent to its destination.

Filter plugins can:

  • Parse unstructured data: Like Apache logs using Grok.
  • Mutate fields: Rename, remove, or add new fields.
  • Add geographic data: Based on IP addresses using GeoIP.
  • Perform conditional logic: Process data differently based on its content.

Filter Example: Grok Parser

The grok filter is incredibly powerful for parsing unstructured log data into structured fields. It uses regular expressions but with pre-defined patterns for common log formats.

This example uses the COMBINEDAPACHELOG pattern to parse a typical Apache web server log line, extracting fields like IP address, timestamp, request, and status code.

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
}

Output Stage: Sending Data

Finally, the output stage is where Logstash sends the processed events. An event can be sent to multiple outputs simultaneously.

Common output destinations include:

  • Elasticsearch: The most common destination for further indexing and search.
  • Stdout: For debugging and testing your pipeline.
  • File: Writing processed data to a new file.
  • Kafka/Redis: For queuing or further processing by other systems.

Output Example: To Elasticsearch

This is a standard output configuration to send your processed data to an Elasticsearch cluster. You specify the hosts (your Elasticsearch node addresses) and the index name.

The %{+YYYY.MM.dd} syntax dynamically creates daily indices, which is a common practice for time-series data.

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "my-logs-%{+YYYY.MM.dd}"
  }
}

Building a Full Pipeline

Now, let's combine all three stages into a single, complete Logstash configuration file. This pipeline reads Nginx access logs, parses them with Grok, and then sends the structured data to Elasticsearch.

This configuration would typically be saved as a .conf file, e.g., nginx-pipeline.conf.

input {
  file {
    path => "/var/log/nginx/access.log"
    start_position => "beginning"
  }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "nginx-access-%{+YYYY.MM.dd}"
  }
}

Running Logstash

To run your Logstash pipeline, you typically execute the logstash command-line tool, pointing it to your configuration file.

Before running it for real, it's good practice to test your configuration file for syntax errors using the --config.test_and_exit flag. This ensures your pipeline is valid before processing any data.

bin/logstash -f nginx-pipeline.conf --config.test_and_exit

# To run the pipeline
bin/logstash -f nginx-pipeline.conf

Quick Check

Which of the following statements about Logstash's pipeline stages are TRUE?

Logstash in Review

In this lesson, we explored Logstash, a crucial part of the Elastic Stack for data ingestion. We learned about its core pipeline concept, comprising input, filter, and output stages.

You now understand how Logstash collects data from various sources, transforms it using powerful filters like Grok, and then dispatches it to destinations such as Elasticsearch. This capability is essential for preparing diverse data for effective search and analysis.

Часто задаваемые вопросы

Урок «Logstash для загрузки данных» бесплатный?

Да — полный текст урока «Logstash для загрузки данных» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Elasticsearch & Full Text Search Systems, подпишись на CoddyKit PRO. Курс Elasticsearch & Full Text Search Systems содержит 4 уроков всего.

Чему я научусь в уроке «Logstash для загрузки данных»?

Научитесь использовать Logstash для сбора, разбора и преобразования данных из разных источников перед их индексированием в Elasticsearch. Ты практикуешь Elasticsearch & Full Text Search Systems с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Elasticsearch & Full Text Search Systems?

Предыдущий опыт не требуется. Elasticsearch & Full Text Search Systems на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Logstash для загрузки данных»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Elasticsearch & Full Text Search Systems?

Да. Каждый урок Elasticsearch & Full Text Search Systems включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Kibana для визуализации
  2. Logstash для загрузки данных
  3. Интеграция с приложениями (клиентами)
  4. Beats для лёгкой передачи данных
← Назад к Elasticsearch & Full Text Search Systems