Logstash-quick-guide

提供:Dev Guides
移動先:案内検索

Logstash-はじめに

Logstashは、ログまたはイベントを収集、処理、生成するためのフィルター/パイプパターンに基づくツールです。 これは、さまざまなソースからのログとイベントのリアルタイム分析の一元化と作成に役立ちます。

LogstashはJVMで実行されるJRubyプログラミング言語で書かれているため、異なるプラットフォームでLogstashを実行できます。 ほとんどすべてのタイプのソースから、ログ、パケット、イベント、トランザクション、タイムスタンプデータなどのさまざまなタイプのデータを収集します。 データソースは、ソーシャルデータ、Eコマース、ニュース記事、CRM、ゲームデータ、Webトレンド、財務データ、モノのインターネット、モバイルデバイスなどです。

Logstashの一般的な機能

Logstashの一般的な機能は次のとおりです-

  • Logstashは、さまざまなソースからデータを収集し、複数の宛先に送信できます。
  • Logstashは、Apacheログ、Windowsイベントログ、ネットワークプロトコル上のデータ、標準入力からのデータなど、あらゆる種類のログデータを処理できます。
  • Logstashは、http要求と応答データも処理できます。
  • Logstashにはさまざまなフィルターが用意されており、ユーザーはデータを解析および変換することで、データのより多くの意味を見つけることができます。
  • Logstashは、モノのインターネットでセンサーデータを処理するためにも使用できます。
  • Logstashはオープンソースであり、Apacheライセンスバージョン2.0で利用できます。

Logstashの主要な概念

Logstashの主要な概念は次のとおりです-

イベントオブジェクト

これは、Logstashパイプラインのデータフローをカプセル化するLogstashのメインオブジェクトです。 Logstashはこのオブジェクトを使用して入力データを保存し、フィルターステージ中に作成されたフィールドを追加します。

Logstashは、イベントを操作する開発者にイベントAPIを提供します。 このチュートリアルでは、このイベントは、ログデータイベント、ログイベント、ログデータ、入力ログデータ、出力ログデータなどのさまざまな名前で参照されます。

パイプライン

Logstashの入力から出力までのデータフローステージで構成されます。 入力データはパイプラインに入力され、イベントの形式で処理されます。 次に、ユーザーまたはエンドシステムの望ましい形式で出力先に送信します。

入力

これはLogstashパイプラインの最初の段階であり、Logstashでデータを取得してさらに処理するために使用されます。 Logstashは、さまざまなプラットフォームからデータを取得するためのさまざまなプラグインを提供します。 最も一般的に使用されるプラグインには、File、Syslog、Redis、Beatsがあります。

フィルタ

これは、イベントの実際の処理が行われるLogstashの中間段階です。 開発者は、Logstashによる事前定義の正規表現パターンを使用して、イベント内のフィールドと受け入れられた入力イベントの基準を区別するためのシーケンスを作成できます。

Logstashは、開発者がイベントを解析して望ましい構造に変換するのに役立つさまざまなプラグインを提供します。 最も一般的に使用されるフィルタープラグインには、Grok、Mutate、Drop、Clone、Geoipがあります。

出力

これはLogstashパイプラインの最後の段階であり、出力イベントを宛先システムに必要な構造にフォーマットできます。 最後に、プラグインを使用して宛先への処理が完了した後、出力イベントを送信します。 最も一般的に使用されるプラグインには、Elasticsearch、File、Graphite、Statsdなどがあります。

Logstashの利点

以下のポイントは、Logstashのさまざまな利点を説明しています。

  • Logstashは、入力イベントのさまざまなフィールドを識別および解析するための正規表現パターンシーケンスを提供します。
  • Logstashは、ロギングデータを抽出するためのさまざまなWebサーバーとデータソースをサポートしています。
  • Logstashには、ロギングデータを解析してユーザーが希望する形式に変換するための複数のプラグインが用意されています。
  • Logstashは一元化されているため、さまざまなサーバーからのデータの処理と収集が簡単になります。
  • Logstashは、ロギングイベントの宛先ソースとして、多くのデータベース、ネットワークプロトコル、およびその他のサービスをサポートしています。
  • LogstashはHTTPプロトコルを使用します。これにより、ユーザーはロックステップでLogstashをアップグレードしなくてもElasticsearchバージョンをアップグレードできます。

Logstashの欠点

以下のポイントは、Logstashのさまざまな欠点を説明しています。

  • Logstashはhttpを使用します。これは、ロギングデータの処理に悪影響を及ぼします。
  • Logstashの操作は、入力ログデータを十分に理解して分析する必要があるため、少し複雑になる場合があります。
  • フィルタープラグインは汎用ではないため、ユーザーは解析のエラーを回避するために正しいパターンのシーケンスを見つける必要がある場合があります。

次の章では、ELKスタックとは何か、それがLogstashにどのように役立つかを理解します。

Logstash-ELKスタック

ELKは* Elasticsearch、Logstash、および *Kibana の略です。 ELKスタックでは、Logstashはさまざまな入力ソースからロギングデータまたはその他のイベントを抽出します。 イベントを処理し、後でElasticsearchに保存します。 Kibanaは、Elasticsearchのログデータにアクセスして視覚化するWebインターフェースです。

ELK

LogstashとElasticsearch

Logstashは、Elasticsearchにログイベントを読み書きするための入力および出力Elasticsearchプラグインを提供します。 出力先としてのElasticsearchも、Kibanaとの互換性のため、Elasticsearch Companyによって推奨されています。 Logstashは、httpプロトコルを介してデータをElasticsearchに送信します。

Elasticsearchは、さまざまなソースまたはLogstashインスタンスから集中型Elasticsearchエンジンにデータをアップロードするのに役立つバルクアップロード機能を提供します。 ELKには、他のDevOpsソリューションに比べて次の利点があります-

  • ELKスタックは管理が簡単で、ペタバイトのイベントを処理するために拡張できます。
  • ELKスタックアーキテクチャは非常に柔軟で、Hadoopとの統合を提供します。 Hadoopは、主にアーカイブの目的で使用されます。 Logstashはflumeを使用してHadoopに直接接続でき、ElasticsearchはHadoopに接続するための es-hadoop という名前のコネクタを提供します。
  • ELKの所有権の総コストは、他の選択肢よりもはるかに低くなっています。

LogstashとKibana

KibanaはLogstashと直接対話するのではなく、ELKスタックのElasticsearchであるデータソースを介して対話します。 Logstashはすべてのソースからデータを収集し、Elasticsearchはそれを非常に高速で分析し、Kibanaはそのデータに関する実用的な洞察を提供します。

KibanaはWebベースの視覚化ツールであり、開発者などが、ElasticsearchエンジンのLogstashによって収集された大量のイベントの変動を分析するのに役立ちます。 この視覚化により、入力ソースのエラーまたはその他の重要なイベントの傾向の変化を簡単に予測または確認できます。

Logstash-インストール

システムにLogstashをインストールするには、以下の手順に従う必要があります-

  • ステップ1 *-コンピューターにインストールされているJavaのバージョンを確認します。 Java 9と互換性がないため、Java 8にする必要があります。 これを確認するには-

Windowsオペレーティングシステム(OS)で(コマンドプロンプトを使用して)-

> java -version

UNIX OSの場合(ターミナルを使用)-

$ echo $JAVA_HOME
  • ステップ2 *-Logstashをダウンロード-

[[1]]

  • Windows OSの場合、ZIPファイルをダウンロードします。
  • UNIX OSの場合、TARファイルをダウンロードします。
  • Debian OSの場合、DEBファイルをダウンロードします。
  • Red Hatおよびその他のLinuxディストリビューションの場合、RPNファイルをダウンロードします。
  • APTおよびYumユーティリティを使用して、多くのLinuxディストリビューションにLogstashをインストールすることもできます。
  • ステップ3 *-Logstashのインストールプロセスは非常に簡単です。 さまざまなプラットフォームにLogstashをインストールする方法を見てみましょう。

注意-インストールフォルダに空白やコロンを入れないでください。

  • Windows OS -zipパッケージを解凍すると、Logstashがインストールされます。
  • UNIX OS -任意の場所でtarファイルを抽出すると、Logstashがインストールされます。
$tar –xvf logstash-5.0.2.tar.gz
  • Linux OS用のAPTユーティリティの使用-*
  • 公開署名キーをダウンロードしてインストールします-
$ wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
  • リポジトリ定義を保存します-
$ echo "deb https://artifacts.elastic.co/packages/5.x/apt stable main" | sudo
   tee -a/etc/apt/sources.list.d/elastic-5.x.list
  • 更新を実行する-
$ sudo apt-get update
  • 今、あなたは次のコマンドを使用してインストールすることができます-
$ sudo apt-get install logstash
  • Debian Linux OS用のYUMユーティリティの使用*-
  • 公開署名キーをダウンロードしてインストールします-
$ rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
  • o「/etc/yum.repos.d/」ディレクトリで、接尾辞が.repoのファイルに次のテキストを追加します。 たとえば、 logstash.repo
[logstash-5.x]
name = Elastic repository for 5.x packages
baseurl = https://artifacts.elastic.co/packages/5.x/yum
gpgcheck = 1
gpgkey = https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled = 1
autorefresh = 1
type = rpm-md
  • これで、次のコマンドを使用してLogstashをインストールできます-
$ sudo yum install logstash

ステップ4 *-Logstashホームディレクトリに移動します。 binフォルダー内で、Windowsの場合は *elasticsearch.bat ファイルを実行します。または、コマンドプロンプトとターミナルを使用して同じことを実行できます。 UNIXでは、Logstashファイルを実行します。

入力ソース、出力ソース、オプションのフィルターを指定する必要があります。 インストールを検証するために、入力ソースとして標準入力ストリーム(stdin)を、出力ソースとして標準出力ストリーム(stdout)を使用して、基本構成で実行できます。 –e オプションを使用して、コマンドラインで構成を指定することもできます。

  • Windowsの場合-*
> cd logstash-5.0.1/bin
> Logstash -e 'input { stdin { } } output { stdout {} }'
  • Linuxの場合-*
$ cd logstash-5.0.1/bin
$ ./logstash -e 'input { stdin { } } output { stdout {} }'

注意-Windowsの場合、JAVA_HOMEが設定されていないことを示すエラーが表示される場合があります。 これには、環境変数で「C:\ Program Files \ Java \ jre1.8.0_111」またはjavaをインストールした場所に設定してください。

ステップ5 *-Logstash Webインターフェースのデフォルトポートは9600〜9700で、 *logstash-5.0.1 \ config \ logstash.ymlhttp.port として定義され、最初の使用可能なポートを取得します。与えられた範囲。

Logstashサーバーが稼働しているかどうかは、 http://localhost:9600 を参照するか、ポートが異なるかどうかを確認してから、コマンドプロンプトまたはターミナルを確認してください。 割り当てられたポートは、「Logstash APIエンドポイントが正常に開始されました\ {:port⇒9600}」と表示されます。 それは、次の方法でインストールされたLogstashに関する情報を含むJSONオブジェクトを返します-

{
   "host":"manu-PC",
   "version":"5.0.1",
   "http_address":"127.0.0.1:9600",
   "build_date":"2016-11-11T22:28:04+00:00",
   "build_sha":"2d8d6263dd09417793f2a0c6d5ee702063b5fada",
   "build_snapshot":false
}

Logstash-内部アーキテクチャ

この章では、Logstashの内部アーキテクチャとさまざまなコンポーネントについて説明します。

Logstashサービスアーキテクチャ

Logstashは、さまざまなサーバーおよびデータソースからのログを処理し、荷送人として動作します。 荷送人はログを収集するために使用され、これらはすべての入力ソースにインストールされます。 Redis、Kafka または RabbitMQ などのブローカーは、インデクサーのデータを保持するバッファーです。フェールオーバーインスタンスとして複数のブローカーが存在する場合があります。

*Lucene* などのインデクサーを使用してログのインデックスを作成し、検索パフォーマンスを向上させてから、出力をElasticsearchまたはその他の出力先に保存します。 出力ストレージのデータは、Kibanaおよびその他の視覚化ソフトウェアで使用できます。

Logstashサービスアーキテクチャ

Logstash内部アーキテクチャ

Logstashパイプラインは、3つのコンポーネント Input、Filters および Output で構成されています。 入力部分は、 Apache Tomcat Server のログフォルダーなどの入力データソースを指定してアクセスする役割を果たします。

Logstash内部アーキテクチャ

Logstashパイプラインを説明する例

Logstash構成ファイルには、Logstashの3つのコンポーネントに関する詳細が含まれています。 この場合、 Logstash.conf というファイル名を作成しています。

次の構成では、入力ログ「inlog.log」からデータをキャプチャし、フィルターなしで出力ログ「outlog.log」に書き込みます。

Logstash.conf

Logstash構成ファイルは、入力プラグインを使用して inlog.log ファイルからデータをコピーし、出力プラグインを使用して outlog.log ファイルにログデータをフラッシュします。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/inlog.log"
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/outlog.log"
   }
}

Logstashを実行する

Logstashは –f オプションを使用して構成ファイルを指定します。

C:\logstash\bin> logstash –f logstash.conf

inlog.log

次のコードブロックは、入力ログデータを示しています。

Hello finddevguides.com

outlog.log

Logstashの出力には、メッセージフィールドの入力データが含まれます。 Logstashは、タイムスタンプ、入力ソースのパス、バージョン、ホスト、タグなどの他のフィールドも出力に追加します。

{
   "path":"C:/tpwork/logstash/bin/log/inlog1.log",
   "@timestamp":"2016-12-13T02:28:38.763Z",
   "@version":"1", "host":"Dell-PC",
   "message":" Hello finddevguides.com", "tags":[]
}

可能な限り、Logstashの出力には、入力ログから提供されたデータ以上のものが含まれています。 出力には、ソースパス、タイムスタンプ、バージョン、ホスト名、タグが含まれます。これらは、エラーなどの追加メッセージを表すために使用されます。

フィルターを使用してデータを処理し、ニーズに合わせてデータを有用にすることができます。 次の例では、フィルターを使用してデータを取得します。これは、GETまたはPOSTなどの動詞の後に Unique Resource Identifier が続くデータのみに出力を制限します。

Logstash.conf

このLogstash構成では、入力データを除外するために grok という名前のフィルターを追加します。 パターンシーケンスの入力ログと一致する入力ログイベントは、エラーのある出力先にのみ到達します。 Logstashは、出力イベントに「_grokparsefailure」という名前のタグを追加しますが、これはgrokフィルターパターンシーケンスと一致しません。

Logstashは、Apacheなどの一般的なサーバーログを解析するための多くの組み込み正規表現パターンを提供します。 ここで使用するパターンは、get、postなどの動詞の後に均一なリソース識別子が続くことを想定しています。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/inlog2.log"
   }
}
filter {
   grok {
      match => {"message" => "%{WORD:verb} %{URIPATHPARAM:uri}"}
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/outlog2.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

C:\logstash\bin> logstash –f  Logstash.conf

inlog2.log

入力ファイルには、デフォルトの区切り文字、つまり改行区切り文字で区切られた2つのイベントが含まれています。 最初のイベントはGROkで指定されたパターンと一致し、2番目のイベントは一致しません。

GET/finddevguides/Logstash
Input 1234

outlog2.log

grokフィルターパターンと一致しないため、2番目の出力イベントに「_grokparsefailure」タグが含まれていることがわかります。 ユーザーは、出力プラグインで 'if' 条件を使用することにより、これらの一致しないイベントを出力から削除することもできます。

{
   "path":"C:/tpwork/logstash/bin/log/inlog2.log",
   "@timestamp":"2016-12-13T02:47:10.352Z","@version":"1","host":"Dell-PC","verb":"GET",
   "message":"GET/finddevguides/logstash", "uri":"/finddevguides/logstash", "tags":[]
}
{
   "path":"C:/tpwork/logstash/bin/log/inlog2.log",
   "@timestamp":"2016-12-13T02:48:12.418Z", "@version":"1", "host":"Dell-PC",
   "message":"t 1234\r", "tags":["_grokparsefailure"]
}

Logstash-ログの収集

さまざまなサーバーまたはデータソースからのログは、配送業者を使用して収集されます。 配送業者はサーバーにインストールされたLogstashのインスタンスであり、サーバーログにアクセスして特定の出力場所に送信します。

主に出力をElasticsearchに送信してストレージに送信します。 Logstashは次のソースから入力を取ります-

  • STDIN
  • syslog
  • ファイル
  • TCP/UDP
  • Microsoft Windowsイベントログ
  • Websocket
  • Zeromq
  • カスタマイズされた拡張機能

Apache Tomcat 7サーバーを使用したログの収集

この例では、ファイル入力プラグインを使用してWindowsにインストールされたApache Tomcat 7サーバーのログを収集し、他のログに送信しています。

logstash.conf

ここで、Logstashは、ローカルにインストールされたApache Tomcat 7のアクセスログにアクセスするように構成されています。 正規表現パターンは、ファイルプラグインのパス設定で使用され、ログファイルからデータを取得します。 これには名前に「アクセス」が含まれており、Apacheタイプが追加されます。これにより、Apacheイベントを集中宛先ソースの他のイベントと区別できます。 最後に、出力イベントがoutput.logに表示されます。

input {
   file {
      path => "C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/*access*"
      type => "apache"
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

C:\logstash\bin> logstash –f  Logstash.conf

Apache Tomcatログ

Apache TomcatサーバーとそのWebアプリ( http://localhost:8080 )にアクセスしてログを生成します。 ログ内の更新されたデータは、Logstashによってリアルタイムで読み取られ、構成ファイルで指定されたoutput.logに隠されます。

Apache Tomcatは、日付に従って新しいアクセスログファイルを生成し、そこにアクセスイベントを記録します。 この例では、Apache Tomcatの logs ディレクトリにあるlocalhost_access_log.2016-12-24.txtでした。

0:0:0:0:0:0:0:1 - - [
   25/Dec/2016:18:37:00 +0800] "GET/HTTP/1.1" 200 11418
0:0:0:0:0:0:0:1 - munish [
   25/Dec/2016:18:37:02 +0800] "GET/manager/html HTTP/1.1" 200 17472
0:0:0:0:0:0:0:1 - - [
   25/Dec/2016:18:37:08 +0800] "GET/docs/HTTP/1.1" 200 19373
0:0:0:0:0:0:0:1 - - [
   25/Dec/2016:18:37:10 +0800] "GET/docs/introductionl HTTP/1.1" 200 15399

output.log

出力イベントで確認できます。タイプフィールドが追加され、メッセージフィールドにイベントが表示されます。

{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   localhost_access_log.2016-12-25.txt",
   "@timestamp":"2016-12-25T10:37:00.363Z","@version":"1","host":"Dell-PC",
   "message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:00 +0800] \"GET/
   HTTP/1.1\" 200 11418\r","type":"apache","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:10.407Z",
   "@version":"1","host":"Dell-PC",
   "message":"0:0:0:0:0:0:0:1 - munish [25/Dec/2016:18:37:02 +0800] \"GET/
   manager/html HTTP/1.1\" 200 17472\r","type":"apache","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:10.407Z",
   "@version":"1","host":"Dell-PC",
   "message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:08 +0800] \"GET/docs/
   HTTP/1.1\" 200 19373\r","type":"apache","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   localhost_access_log.2016-12-25.txt","@timestamp":"2016-12-25T10:37:20.436Z",
   "@version":"1","host":"Dell-PC",
   "message":"0:0:0:0:0:0:0:1 - - [25/Dec/2016:18:37:10 +0800] \"GET/docs/
   introductionl HTTP/1.1\" 200 15399\r","type":"apache","tags":[]
}

STDINプラグインを使用したログの収集

このセクションでは、* STDINプラグイン*を使用してログを収集する別の例を説明します。

logstash.conf

これは非常に単純な例です。Logstashは、ユーザーが標準入力で入力したイベントを読み取ります。 私たちの場合、イベントをoutput.logファイルに保存するのはコマンドプロンプトです。

input {
   stdin{}
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

C:\logstash\bin> logstash –f  Logstash.conf

コマンドプロンプトに次のテキストを書きます-

ユーザーは次の2行を入力しました。 Logstashは、イベントを区切り文字設定で区切ります。デフォルトの値は「\ n」です。 ユーザーは、ファイルプラグインの区切り文字の値を変更することで変更できます。

finddevguides.com welcomes you
Simply easy learning

output.log

次のコードブロックは、出力ログデータを示しています。

{
   "@timestamp":"2016-12-25T11:41:16.518Z","@version":"1","host":"Dell-PC",
   "message":"tutrialspoint.com welcomes you\r","tags":[]
}
{
   "@timestamp":"2016-12-25T11:41:53.396Z","@version":"1","host":"Dell-PC",
   "message":"simply easy learning\r","tags":[]
}

Logstash-サポートされる入力

Logstashは、さまざまなソースからの膨大な範囲のログをサポートしています。 以下で説明するように、有名なソースで動作しています。

メトリックからログを収集する

システムイベントおよびその他の時間アクティビティはメトリックに記録されます。 Logstashは、システムメトリックからログにアクセスし、フィルターを使用して処理できます。 これは、イベントのライブフィードをカスタマイズされた方法でユーザーに表示するのに役立ちます。 メトリックは、メトリックフィルタの* flush_interval設定*に従って、デフォルトでフラッシュされます。 5秒に設定されています。

Logstashで実行されるイベントを収集して分析し、コマンドプロンプトでライブフィードを表示することにより、Logstashによって生成されたテストメトリックを追跡しています。

logstash.conf

この構成にはジェネレータプラグインが含まれます。これは、テストメトリック用にLogstashによって提供され、解析のためにタイプ設定を「生成」に設定します。 フィルタリングフェーズでは、「if」ステートメントを使用して、生成されたタイプの行のみを処理します。 次に、メトリックプラグインは、メーター設定で指定されたフィールドをカウントします。 メトリックプラグインは、 flush_interval で指定された5秒ごとにカウントをフラッシュします。

最後に、フォーマットに* codecプラグイン*を使用して、コマンドプロンプトなどの標準出力にフィルターイベントを出力します。 Codecプラグインは、[_ events ] [ rate_1m_]値を使用して、1分間のスライディングウィンドウで毎秒のイベントを出力します。

input {
   generator {
        type => "generated"
   }
}
filter {
   if [type] == "generated" {
      metrics {
         meter => "events"
         add_tag => "metric"
      }
   }
}
output {
   # only emit events with the 'metric' tag
   if "metric" in [tags] {
      stdout {
         codec => line { format => "rate: %{[events][rate_1m]}"
      }
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>logsaths –f logstash.conf

stdout(コマンドプロンプト)

rate: 1308.4
rate: 1308.4
rate: 1368.654529135342
rate: 1416.4796003951449
rate: 1464.974293984808
rate: 1523.3119444107458
rate: 1564.1602979542715
rate: 1610.6496496890895
rate: 1645.2184750334154
rate: 1688.7768007612485
rate: 1714.652283095914
rate: 1752.5150680019278
rate: 1785.9432934744932
rate: 1806.912181962126
rate: 1836.0070454626025
rate: 1849.5669494173826
rate: 1871.3814756851832
rate: 1883.3443123790712
rate: 1906.4879113216743
rate: 1925.9420717997118
rate: 1934.166137658981
rate: 1954.3176526556897
rate: 1957.0107444542625

Webサーバーからログを収集する

Webサーバーは、ユーザーアクセスとエラーに関する多数のログを生成します。 Logstashは、入力プラグインを使用してさまざまなサーバーからログを抽出し、それらを一元化された場所に保管するのに役立ちます。

ローカルApache Tomcatサーバーの* stderrログ*からデータを抽出し、output.logに隠します。

logstash.conf

このLogstash構成ファイルは、Logstashにapacheエラーログを読み取り、「apache-error」という名前のタグを追加するよう指示します。 ファイル出力プラグインを使用して、単にoutput.logに送信できます。

input {
   file {
      path => "C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/*stderr*"
      type => "apache-error"
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>Logstash –f Logstash.conf

入力ログのサンプル

これはサンプルの* stderrログ*で、Apache Tomcatでサーバーイベントが発生したときに生成されます。

C:\ Program Files \ Apache Software Foundation \ Tomcat 7.0 \ logs \ tomcat7-stderr.2016-12-25.log

Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-9999"]
Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 823 ms

output.log

{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z",
   "@version":"1","host":"Dell-PC",
   "message":"Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start\r",
   "type":"apache-error","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z",
   "@version":"1","host":"Dell-PC",
   "message":"INFO: Starting ProtocolHandler [
      \"ajp-bio-8009\"]\r","type":"apache-error","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z",
   "@version":"1","host":"Dell-PC",
   "message":"Dec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start\r",
   "type":"apache-error","tags":[]
}
{
   "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/
   tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z",
   "@version":"1","host":"Dell-PC",
   "message":"INFO: Server startup in 823 ms\r","type":"apache-error","tags":[]
}

データソースからログを収集する

まず、ロギング用にMySQLを構成する方法を理解しましょう。 [mysqld]の下のMySQLデータベースサーバーの* my.iniファイル*に次の行を追加します。

Windowsでは、MySQLのインストールディレクトリ内に存在します。

C:\wamp\bin\mysql\mysql5.7.11

UNIXでは、/etc/mysql/my.cnfにあります。

general_log_file   = "C:/wamp/logs/queries.log"
general_log = 1

logstash.conf

この設定ファイルでは、ファイルプラグインを使用してMySQLログを読み取り、ouput.logに書き込みます。

input {
   file {
      path => "C:/wamp/logs/queries.log"
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

querys.log

これは、MySQLデータベースで実行されたクエリによって生成されたログです。

2016-12-25T13:05:36.854619Z   2 Query       select * from test1_users
2016-12-25T13:05:51.822475Z    2 Query  select count(*) from users
2016-12-25T13:05:59.998942Z    2 Query         select count(*) from test1_users

output.log

{
   "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:05:37.905Z",
   "@version":"1","host":"Dell-PC",
   "message":"2016-12-25T13:05:36.854619Z    2 Query\tselect * from test1_users",
   "tags":[]
}
{
   "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:05:51.938Z",
   "@version":"1","host":"Dell-PC",
   "message":"2016-12-25T13:05:51.822475Z    2 Query\tselect count(*) from users",
   "tags":[]
}
{
   "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:06:00.950Z",
   "@version":"1","host":"Dell-PC",
   "message":"2016-12-25T13:05:59.998942Z    2 Query\tselect count(*) from test1_users",
   "tags":[]
}

Logstash-ログの解析

Logstashは入力プラグインを使用してログを受信し、フィルタープラグインを使用してデータを解析および変換します。 ログの解析と変換は、出力先に存在するシステムに従って実行されます。 Logstashはロギングデータを解析し、必要なフィールドのみを転送します。 後で、これらのフィールドは、宛先システムの互換性のある理解可能な形式に変換されます。

ログを解析する方法は?

ログの解析は、 GROK (知識のグラフィカルな表現)パターンを使用して実行され、Githubで見つけることができます-

[[2]]

Logstashは、ログのデータを、指定されたGROKパターンまたは「%\ {COMBINEDAPACHELOG}」のようなログを解析するためのパターンシーケンスと一致させます。これは、Apacheログに一般的に使用されます。

解析されたデータはより構造化されており、検索やクエリの実行が簡単です。 Logstashは、入力ログで指定されたGROKパターンを検索し、ログから一致する行を抽出します。 GROKデバッガーを使用して、GROKパターンをテストできます。

GROKパターンの構文は%\ {SYNTAX:SEMANTIC}です。 Logstash GROKフィルターは、次の形式で書かれています-

  • %\ {PATTERN:FieldName} *

ここで、PATTERNはGROKパターンを表し、fieldnameはフィールドの名前であり、出力の解析済みデータを表します。

たとえば、オンラインGROKデバッガーhttps://grokdebug.herokuapp.com/を使用する

入力

ログのエラー行のサンプル-

[Wed Dec 07 21:54:54.048805 2016] [:error] [pid 1234:tid 3456829102]
   [client 192.168.1.1:25007] JSP Notice:  Undefined index: abc in
  /home/manu/tpworks/finddevguides.com/index.jsp on line 11

GROKパターンシーケンス

このGROKパターンシーケンスは、タイムスタンプの後にログレベル、プロセスID、トランザクションID、エラーメッセージが続くログイベントに一致します。

\[(%{DAY:day} %{MONTH:month} %{MONTHDAY} %{TIME} %{YEAR})\] \[.*:%{LOGLEVEL:loglevel}\]
   \[pid %{NUMBER:pid}:tid %{NUMBER:tid}\] \[client %{IP:clientip}:.*\]
   %{GREEDYDATA:errormsg}

出力

出力はJSON形式です。

{
   "day": [
      "Wed"
   ],
   "month": [
      "Dec"
   ],
   "loglevel": [
      "error"
   ],
   "pid": [
      "1234"
   ],
   "tid": [
      "3456829102"
   ],
   "clientip": [
      "192.168.1.1"
   ],
   "errormsg": [
      "JSP Notice:  Undefined index: abc in
     /home/manu/tpworks/finddevguides.com/index.jsp on line 11"
   ]
}

Logstash-フィルター

Logstashは、入力と出力の間のパイプラインの途中でフィルターを使用します。 Logstashメジャーのフィルターは、 Apache-Access などのイベントを操作および作成します。 Logstashでイベントを管理するために使用される多くのフィルタープラグイン。 ここで、 Logstash Aggregate Filter の例では、データベース内のすべてのSQLトランザクションの期間をフィルタリングし、合計時間を計算しています。

集約フィルタープラグインのインストール

Logstash-pluginユーティリティーを使用した集約フィルタープラグインのインストール。 Logstashプラグインは、Logstashの* binフォルダー*にあるWindows用のバッチファイルです。

>logstash-plugin install logstash-filter-aggregate

logstash.conf

この構成では、トランザクションの合計期間を*初期化、増分、生成*するための3つの「if」ステートメント、つまり *sql_duration を確認できます。 集約プラグインは、入力ログのすべてのイベントに存在するsql_durationを追加するために使用されます。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input.log"
   }
}
filter {
   grok {
      match => [
         "message", "%{LOGLEVEL:loglevel} -
            %{NOTSPACE:taskid} - %{NOTSPACE:logger} -
            %{WORD:label}( - %{INT:duration:int})?"
      ]
   }
   if [logger] == "TRANSACTION_START" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] = 0"
         map_action => "create"
      }
   }
   if [logger] == "SQL" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] ||= 0 ;
            map['sql_duration'] += event.get('duration')"
      }
   }
   if [logger] == "TRANSACTION_END" {
      aggregate {
         task_id => "%{taskid}"
         code => "event.set('sql_duration', map['sql_duration'])"
         end_of_task => true
         timeout => 120
      }
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>logstash –f logstash.conf

input.log

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
INFO - 48566 - SQL - transaction1 - 320
INFO - 48566 - SQL - transaction1 - 200
INFO - 48566 - TRANSACTION_END - end

output.log

構成ファイルで指定されているように、ロガーがある最後の「if」ステートメント– TRANSACTION_END。トランザクションの合計時間またはsql_durationを出力します。 これは、output.logで黄色で強調表示されています。

{
   "path":"C:/tpwork/logstash/bin/log/input.log","@timestamp": "2016-12-22T19:04:37.214Z",
   "loglevel":"INFO","logger":"TRANSACTION_START","@version": "1","host":"wcnlab-PC",
   "message":"8566 - TRANSACTION_START - start\r","tags":[]
}
{
   "duration":320,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-22T19:04:38.366Z","loglevel":"INFO","logger":"SQL",
   "@version":"1","host":"wcnlab-PC","label":"transaction1",
   "message":" INFO - 48566 - SQL - transaction1 - 320\r","taskid":"48566","tags":[]
}
{
   "duration":200,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-22T19:04:38.373Z","loglevel":"INFO","logger":"SQL",
   "@version":"1","host":"wcnlab-PC","label":"transaction1",
   "message":" INFO - 48566 - SQL - transaction1 - 200\r","taskid":"48566","tags":[]
}
{
   "sql_duration":520,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-22T19:04:38.380Z","loglevel":"INFO","logger":"TRANSACTION_END",
   "@version":"1","host":"wcnlab-PC","label":"end",
   "message":" INFO - 48566 - TRANSACTION_END - end\r","taskid":"48566","tags":[]
}

Logstash-ログの変換

Logstashは、解析されたログを変換するためのさまざまなプラグインを提供します。 これらのプラグインは、出力システムでの理解とクエリを改善するために、ログ内のフィールドを*追加、削除、*および*更新*できます。

*Mutate Plugin* を使用して、入力ログのすべての行にフィールド名ユーザーを追加しています。

Mutate Filterプラグインをインストールする

mutate filterプラグインをインストールするには。次のコマンドを使用できます。

>Logstash-plugin install Logstash-filter-mutate

logstash.conf

この設定ファイルでは、新しいフィールドを追加するために、Aggregateプラグインの後にMutateプラグインが追加されます。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input.log"
   }
}
filter {
   grok {
      match => [ "message", "%{LOGLEVEL:loglevel} -
         %{NOTSPACE:taskid} - %{NOTSPACE:logger} -
         %{WORD:label}( - %{INT:duration:int})?" ]
   }
   if [logger] == "TRANSACTION_START" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] = 0"
         map_action => "create"
      }
   }
   if [logger] == "SQL" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] ||= 0 ;
            map['sql_duration'] += event.get('duration')"
      }
   }
   if [logger] == "TRANSACTION_END" {
      aggregate {
         task_id => "%{taskid}"
         code => "event.set('sql_duration', map['sql_duration'])"
         end_of_task => true
         timeout => 120
      }
   }
   mutate {
      add_field => {"user" => "finddevguides.com"}
   }
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output.log"
   }
}

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>logstash –f logstash.conf

input.log

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
INFO - 48566 - SQL - transaction1 - 320
INFO - 48566 - SQL - transaction1 - 200
INFO - 48566 - TRANSACTION_END - end

output.log

出力イベントに「user」という名前の新しいフィールドがあることがわかります。

{
   "path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-25T19:55:37.383Z",
   "@version":"1",
   "host":"wcnlab-PC",
   "message":"NFO - 48566 - TRANSACTION_START - start\r",
   "user":"finddevguides.com","tags":["_grokparsefailure"]
}
{
   "duration":320,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-25T19:55:37.383Z","loglevel":"INFO","logger":"SQL",
   "@version":"1","host":"wcnlab-PC","label":"transaction1",
   "message":" INFO - 48566 - SQL - transaction1 - 320\r",
   "user":"finddevguides.com","taskid":"48566","tags":[]
}
{
   "duration":200,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-25T19:55:37.399Z","loglevel":"INFO",
   "logger":"SQL","@version":"1","host":"wcnlab-PC","label":"transaction1",
   "message":" INFO - 48566 - SQL - transaction1 - 200\r",
   "user":"finddevguides.com","taskid":"48566","tags":[]
}
{
   "sql_duration":520,"path":"C:/tpwork/logstash/bin/log/input.log",
   "@timestamp":"2016-12-25T19:55:37.399Z","loglevel":"INFO",
   "logger":"TRANSACTION_END","@version":"1","host":"wcnlab-PC","label":"end",
   "message":" INFO - 48566 - TRANSACTION_END - end\r",
   "user":"finddevguides.com","taskid":"48566","tags":[]
}

Logstash-出力ステージ

出力はLogstashパイプラインの最後のステージであり、入力ログから指定された宛先にフィルターデータを送信します。 Logstashには、フィルタリングされたログイベントをさまざまなストレージおよび検索エンジンにスタッシュするための複数の出力プラグインが用意されています。

ログを保存する

Logstashは、フィルタリングされたログを* File、Elasticsearch Engine、stdout、AWS CloudWatchなどに保存できます。 Logstashでは、 TCP、UDP、Websocket などのネットワークプロトコルを使用して、ログイベントをリモートストレージシステムに転送することもできます。

ELKスタックでは、ユーザーはElasticsearchエンジンを使用してログイベントを保存します。 ここで、次の例では、ローカルElasticsearchエンジンのログイベントを生成します。

Elasticsearch Outputプラグインのインストール

次のコマンドでElasticsearch出力プラグインをインストールできます。

>logstash-plugin install Logstash-output-elasticsearch

logstash.conf

この設定ファイルには、ローカルにインストールされたElasticsearchに出力イベントを保存するElasticsearchプラグインが含まれています。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input.log"
   }
}
filter {
   grok {
      match => [ "message", "%{LOGLEVEL:loglevel} -
      %{NOTSPACE:taskid} - %{NOTSPACE:logger} -
      %{WORD:label}( - %{INT:duration:int})?" ]
   }
   if [logger] == "TRANSACTION_START" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] = 0"
         map_action => "create"
      }
   }
   if [logger] == "SQL" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] ||= 0 ;
            map['sql_duration'] += event.get('duration')"
      }
   }
   if [logger] == "TRANSACTION_END" {
      aggregate {
         task_id => "%{taskid}"
         code => "event.set('sql_duration', map['sql_duration'])"
         end_of_task => true
         timeout => 120
      }
   }
   mutate {
      add_field => {"user" => "finddevguides.com"}
   }
}
output {
   elasticsearch {
      hosts => ["127.0.0.1:9200"]
   }
}

Input.log

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
INFO - 48566 - SQL - transaction1 - 320
INFO - 48566 - SQL - transaction1 - 200
INFO - 48566 - TRANSACTION_END - end

LocalhostでElasticsearchを開始します

ローカルホストでElasticsearchを開始するには、次のコマンドを使用する必要があります。

C:\elasticsearch\bin> elasticsearch

Elasticsearchの準備ができたら、ブラウザに次のURLを入力して確認できます。

*http://localhost:9200/*

応答

次のコードブロックは、localhostでのElasticsearchの応答を示しています。

{
   "name" : "Doctor Dorcas",
   "cluster_name" : "elasticsearch",
   "version" : {
      "number" : "2.1.1",
      "build_hash" : "40e2c53a6b6c2972b3d13846e450e66f4375bd71",
      "build_timestamp" : "2015-12-15T13:05:55Z",
      "build_snapshot" : false,
      "lucene_version" : "5.3.1"
   },
   "tagline" : "You Know, for Search"
}

-Elasticsearchの詳細については、次のリンクをクリックしてください。

リンク:/elasticsearch/index [https://www.finddevguides.com/elasticsearch/indexl]

次に、上記のLogstash.confでLogstashを実行します

>Logstash –f Logstash.conf

出力ログに上記のテキストを貼り付けた後、そのテキストはLogstashによってElasticsearchに保存されます。 ブラウザに次のURLを入力して、保存されたデータを確認できます。

*http://localhost:9200/logstash-2017.01.01/_search?pretty*

応答

これは、インデックスLogstash-2017.01.01に保存されているJSON形式のデータです。

{
   "took" : 20,
   "timed_out" : false,
   "_shards" : {
      "total" : 5,
      "successful" : 5,
      "failed" : 0
   },
   "hits" : {
      "total" : 10,
      "max_score" : 1.0,
      "hits" : [ {
         "_index" : "logstash-2017.01.01",
         "_type" : "logs",
         "_id" : "AVlZ9vF8hshdrGm02KOs",
         "_score" : 1.0,
         "_source":{
            "duration":200,"path":"C:/tpwork/logstash/bin/log/input.log",
            "@timestamp":"2017-01-01T12:17:49.140Z","loglevel":"INFO",
            "logger":"SQL","@version":"1","host":"wcnlab-PC",
            "label":"transaction1",
            "message":" INFO - 48566 - SQL - transaction1 - 200\r",
            "user":"finddevguides.com","taskid":"48566","tags":[]
         }
      },
      {
         "_index" : "logstash-2017.01.01",
         "_type" : "logs",
         "_id" : "AVlZ9vF8hshdrGm02KOt",
         "_score" : 1.0,
         "_source":{
            "sql_duration":520,"path":"C:/tpwork/logstash/bin/log/input.log",
            "@timestamp":"2017-01-01T12:17:49.145Z","loglevel":"INFO",
            "logger":"TRANSACTION_END","@version":"1","host":"wcnlab-PC",
            "label":"end",
            "message":" INFO - 48566 - TRANSACTION_END - end\r",
            "user":"finddevguides.com","taskid":"48566","tags":[]
         }
      }
   }
}

Logstash-サポートされる出力

Logstashは、さまざまなデータストアまたは検索エンジンをサポートする複数のプラグインを提供します。 ログの出力イベントは、出力ファイル、標準出力、またはElasticsearchなどの検索エンジンに送信できます。 Logstashでサポートされている出力には3つのタイプがあります。

  • 標準出力
  • ファイル出力
  • ヌル出力

次に、これらのそれぞれについて詳しく説明します。

標準出力(stdout)

フィルターされたログイベントをコマンドラインインターフェイスへのデータストリームとして生成するために使用されます。 次に、データベーストランザクションの合計期間をstdoutに生成する例を示します。

logstash.conf

この構成ファイルには、合計sql_durationを標準出力に書き込むためのstdout出力プラグインが含まれています。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input.log"
   }
}
filter {
   grok {
      match => [
         "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid}
            - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?"
      ]
   }
   if [logger] == "TRANSACTION_START" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] = 0"
         map_action => "create"
      }
   }
   if [logger] == "SQL" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] ||= 0 ;
            map['sql_duration'] += event.get('duration')"
      }
   }
   if [logger] == "TRANSACTION_END" {
      aggregate {
         task_id => "%{taskid}"
         code => "event.set('sql_duration', map['sql_duration'])"
         end_of_task => true
         timeout => 120
      }
   }
}
output {
   if [logger] == "TRANSACTION_END" {
      stdout {
         codec => line{format => "%{sql_duration}"}
      }
   }
}

-まだインストールされていない場合は、集約フィルターをインストールしてください。

>logstash-plugin install Logstash-filter-aggregate

Logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>logstash –f logsatsh.conf

Input.log

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
INFO - 48566 - SQL - transaction1 - 320
INFO - 48566 - SQL - transaction1 - 200
INFO - 48566 - TRANSACTION_END – end
*stdout* (WindowsのコマンドプロンプトまたはUNIXのターミナルになります)

これは、合計sql_duration 320 + 200 = 520です。

520

ファイル出力

Logstashは、フィルターログイベントを出力ファイルに保存することもできます。 上記の例を使用して、出力をSTDOUTではなくファイルに保存します。

logstash.conf

このLogstash構成ファイルは、合計sql_durationを出力ログファイルに保存するようLogstashに指示します。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input1.log"
   }
}
filter {
   grok {
      match => [
         "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} -
            %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?"
      ]
   }
   if [logger] == "TRANSACTION_START" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] = 0"
         map_action => "create"
      }
   }
   if [logger] == "SQL" {
      aggregate {
         task_id => "%{taskid}"
         code => "map['sql_duration'] ||= 0 ;
            map['sql_duration'] += event.get('duration')"
      }
   }
   if [logger] == "TRANSACTION_END" {
      aggregate {
         task_id => "%{taskid}"
         code => "event.set('sql_duration', map['sql_duration'])"
         end_of_task => true
         timeout => 120
      }
   }
}
output {
   if [logger] == "TRANSACTION_END" {
      file {
         path => "C:/tpwork/logstash/bin/log/output.log"
         codec => line{format => "%{sql_duration}"}
      }
   }
}

logstashを実行する

次のコマンドを使用してLogstashを実行できます。

>logstash –f logsatsh.conf

input.log

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
INFO - 48566 - SQL - transaction1 - 320
INFO - 48566 - SQL - transaction1 - 200
INFO - 48566 - TRANSACTION_END – end

output.log

次のコードブロックは、出力ログデータを示しています。

520

ヌル出力

これは、入力およびフィルタープラグインのパフォーマンスを分析するために使用される特別な出力プラグインです。

Logstash-プラグイン

Logstashは、パイプラインの3つのステージすべて(入力、フィルター、出力)にさまざまなプラグインを提供します。 これらのプラグインは、ユーザーがWebサーバー、データベース、ネットワークプロトコルなどのさまざまなソースからログをキャプチャするのに役立ちます。

キャプチャ後、Logstashはデータを解析し、ユーザーの必要に応じて意味のある情報に変換できます。 最後に、Logstashはその意味のある情報をElasticsearch、AWS Cloudwatchなどのさまざまな宛先ソースに送信または保存できます。

入力プラグイン

Logstashの入力プラグインは、ユーザーがさまざまなソースからログを抽出および受信するのに役立ちます。 入力プラグインを使用するための構文は次のとおりです-

Input {
   Plugin name {
      Setting 1……
      Setting 2……..
   }
}

次のコマンドを使用して、入力プラグインをダウンロードできます-

>Logstash-plugin install Logstash-input-<plugin name>

Logstashプラグインユーティリティは、Logstashインストールディレクトリの* binフォルダー*にあります。 次の表に、Logstashが提供する入力プラグインのリストを示します。

Sr.No. Plugin name & Description
1

beats

エラスティックビートフレームワークからログデータまたはイベントを取得します。

2

cloudwatch

Amazon Web Servicesが提供するAPIであるCloudWatchからイベントを抽出します。

3

couchdb_changes

このプラグインを使用して出荷されたcouchdbの_chages URIからのイベント。

4

drupal_dblog

DBLogを有効にしてdrupalのウォッチドッグロギングデータを抽出します。

5

Elasticsearch

Elasticsearchクラスターで実行されたクエリの結果を取得します。

6

eventlog

Windowsイベントログからイベントを取得します。

7

exec

Logstashの入力としてシェルコマンド出力を取得します。

8

file

入力ファイルからイベントを取得します。 これは、Logstashが入力ソースとともにローカルにインストールされ、入力ソースログにアクセスできる場合に役立ちます。

9

generator

ランダムイベントを作成するテスト目的で使用されます。

10

github

GitHub webhookからイベントをキャプチャします。

11

graphite

グラファイトモニタリングツールからメトリックデータを取得します。

12

heartbeat

テストにも使用され、イベントのようなハートビートを生成します

13

http

2つのネットワークプロトコルを介してログイベントを収集するには、これらはhttpとhttpsです。

14

http_poller

イベントへのHTTP API出力をデコードするために使用されます。

15

jdbc

JDBCトランザクションをLogstashのイベントに変換します。

16

jmx

JMXを使用してリモートJavaアプリケーションからメトリックを抽出します。

17

log4j

TCPソケットを介してLog4jのsocketAppenderオブジェクトからイベントをキャプチャします。

18

rss

Logstashの入力イベントとしてのコマンドラインツールの出力。

19

tcp

TCPソケットを介してイベントをキャプチャします。

20

twitter

twitterストリーミングAPIからイベントを収集します。

21

unix

UNIXソケット経由でイベントを収集します。

22

websocket

Websocketプロトコルでイベントをキャプチャします。

23

xmpp

Jabber/xmppプロトコルを介してイベントを読み取ります。

プラグイン設定

すべてのプラグインには固有の設定があり、プラグインでポート、パスなどの重要なフィールドを指定するのに役立ちます。 入力プラグインの設定について説明します。

File

この入力プラグインは、入力ソースに存在するログまたはテキストファイルからイベントを直接抽出するために使用されます。 UNIXのtailコマンドと同様に機能し、最後の読み取りカーソルを保存し、入力ファイルから新しい追加データのみを読み取りますが、star_position設定を使用して変更できます。 この入力プラグインの設定は次のとおりです。

Setting Name Default Value Description
add_field \{} Append a new field to the input event.
close_older 3600 The files having last read time (in seconds) more than the specified in this plugin is closed.
codec “plain” It is used to decode the data before entering into the Logstash pipeline.
delimiter “\n” It is used to specify a new line delimiter.
discover_interval 15 It is the time interval (in seconds) between discovering new files in the specified path.
enable_metric true It is used to enable or disable the reporting and collection of metric for the specified plugin.
exclude It is used to specify the filename or patterns, which should be excluded from input plugin.
Id To specify a unique identity for that plugin instance.
max_open_files It specifies the maximum number of input files by Logstash at any time.
path Specify the path of the files and it can contain the patterns for filename.
start_position “end” You can change to “beginning”, if you want that; initially Logstash should start reading the files from the starting and not only the new log event.
start_interval 1 It specifies the time interval in seconds, after which Logstash checks for the modified files.
tags To add any additional information, like Logstash, it adds "_grokparsefailure" in tags, when any log event failed to comply with the specified grok filter.
type This is a special field, which you can add to an input event and it is useful in filters and kibana.

エラスティックサーチ

この特定のプラグインは、Elasticsearchクラスターで検索クエリの結果を読み取るために使用されます。 以下は、このプラグインで使用される設定を持っています-

Setting Name Default Value Description
add_field \{} Same as in file plugin, it is used to append a field in input event.
ca_file It is used to specify the path of SSL certificate Authority file.
codec “plain” It is used to decode the input events from Elasticsearch before entering in the Logstash pipeline.
docinfo “false” You can change it to true, if you want to extract the additional information like index, type and id from Elasticsearch engine.
docinfo_fields ["_index", "_type", "_id"] You can eliminate any field, which you do not want in your Logstash input.
enable_metric true It is used to enable or disable the reporting and collection of metric for that plugin instance.
hosts It is used to specify the addresses of all elasticsearch engines, which will be the input source of that Logstash instance. The syntax is host:port or IP:port.
Id It is used to give a unique identity number to that specific input plugin instance.
index "logstash-*" It is used to specify the index name or a pattern, which Logstash will monitor by Logstash for input.
password For authentication purposes.
query "\{ \"sort\": [ \"_doc\" ] }" Query for the execution.
ssl false Enable or disable secure socket layer.
tags To add any additional information in input events.
type It is used to classify the input forms so that it will be easy to search all the input events at later stages.
user For authentic purposes.

イベントログ

この入力プラグインは、Windowsサーバーのwin32 APIからデータを読み取ります。 以下は、このプラグインの設定です-

Setting Name Default Value Description
add_field \{} Same as in file plugin, it is used to append a field in input event
codec “plain” It is used to decode the input events from windows; before entering in the Logstash pipeline
logfile ["Application", "Security", "System"] Events required in the input log file
interval 1000 It is in milliseconds and defines the interval between two consecutive checks of new event logs
tags To add any additional information in input events
type It is used to classify the input form a specific plugins to given type, so that it will be easy to search all the input events in later stages

Twitter

この入力プラグインは、ストリーミングAPIからtwitterのフィードを収集するために使用されます。 次の表は、このプラグインの設定について説明しています。

Setting Name Default Value Description
add_field \{} Same as in file plugin, it is used to append a field in input event
codec “plain” It is used to decode the input events from windows; before entering in the Logstash pipeline
consumer_key It contains the twitter app’s consumer key. For more info, visit https://dev.twitter.com/apps/new
consumer_secret It contains the twitter app’s consumer secret key. For more info, visit https://dev.twitter.com/apps/new
enable_metric true It is used to enable or disable the reporting and collection of metric for that plugin instance
follows

It specifies the user ids separated by commas and LogStash checks these users’ status in Twitter.

詳細については、をご覧ください

https://dev.twitter.com

full_tweet false You can change it to true, if you want Logstash to read the full object return from twitter API
id It is used to give a unique identity number to that specific input plugin instance
ignore_retweets False You can change set it true to ignore the retweets in the input twitter feed
keywords It’s an array of keywords, which need to be tracked in the twitters input feed
language It defines the language of the tweets needed by LogStash from input twitter feed. This is an array of identifier, which defines a specific language in twitter
locations To filter out the tweets from input feed according to the location specified. This is an array, which contains longitude and latitude of the location
oauth_token It is a required filed, which contains user oauth token. For more information please visit the following link https://dev.twitter.com/apps
oauth_token_secret It is a required filed, which contains user oauth secret token. For more information please visit the following link https://dev.twitter.com/apps
tags To add any additional information in input events
type It is used to classify the input form a specific plugins to given type, so that it will be easy to search all the input events in later stages

TCP

TCPは、TCPソケットを介してイベントを取得するために使用されます。モード設定で指定されているユーザー接続またはサーバーから読み取ることができます。 次の表は、このプラグインの設定について説明しています-

Setting Name Default Value Description
add_field \{} Same as in file plugin, it is used to append a field in input event
codec “plain” It is used to decode the input events from windows; before entering in the Logstash pipeline
enable_metric true It is used to enable or disable the reporting and collection of metric for that plugin instance
host “0.0.0.0” The address of the server OS the client depends upon
id It contains the twitter app’s consumer key
mode “server” It is used to specify the input source is server or client.
port It defines the port number
ssl_cert It is used to specify the path of SSL certificate
ssl_enable false Enable or disable SSL
ssl_key To specify the path of SSL key file
tags To add any additional information in input events
type It is used to classify the input form a specific plugins to given type, so that it will be easy to search all the input events in later stages

Logstash –出力プラグイン

Logstashはさまざまな出力ソースをサポートし、データベース、ファイル、電子メール、標準出力などのさまざまなテクノロジーでサポートします。

出力プラグインを使用するための構文は次のとおりです-

output {
   Plugin name {
      Setting 1……
      Setting 2……..
   }
}

次のコマンドを使用して、出力プラグインをダウンロードできます-

>logstash-plugin install logstash-output-<plugin name>
  • Logstash-pluginユーティリティ*は、Logstashインストールディレクトリのbinフォルダーにあります。 次の表に、Logstashが提供する出力プラグインを示します。
Sr.No. Plugin Name & Description
1

CloudWatch

このプラグインは、集約されたメトリックデータをAmazon WebサービスのCloudWatchに送信するために使用されます。

2

csv

出力イベントをコンマ区切りで書き込むために使用されます。

3

Elasticsearch

Elasticsearchインデックスに出力ログを保存するために使用されます。

4

email

出力が生成されるときに、通知メールを送信するために使用されます。 ユーザーは、出力に関する情報を電子メールで追加できます。

5

exec

出力イベントに一致するコマンドの実行に使用されます。

6

ganglia

それは、ガンジラのモンドへのメトリックを苦しめます。

7

gelf

GELF形式でGraylog2の出力を生成するために使用されます。

8

google_bigquery

イベントをGoogle BigQueryに出力します。

9

google_cloud_storage

出力イベントをGoogle Cloud Storageに保存します。

10

graphite

Graphiteに出力イベントを保存するために使用されます。

11

graphtastic

Windowsで出力メトリックを書き込むために使用されます。

12

hipchat

出力ログイベントをHipChatに保存するために使用されます。

13

http

出力ログイベントをhttpまたはhttpsエンドポイントに送信するために使用されます。

14

influxdb

InfluxDBに出力イベントを保存するために使用されます。

15

irc

出力イベントをircに書き込むために使用されます。

16

mongodb

出力データをMongoDBに保存します。

17

nagios

パッシブチェックの結果をNagiosに通知するために使用されます。

18

nagios_nsca

NSCAプロトコルを介したパッシブチェックの結果をNagiosに通知するために使用されます。

19

opentsdb

Logstash出力イベントをOpenTSDBに保存します。

20

pipe

出力イベントを別のプログラムの標準入力にストリーミングします。

21

rackspace

出力ログイベントをRackspace Cloudのキューサービスに送信するために使用されます。

22

redis

rpushコマンドを使用して、出力ログデータをRedisキューに送信します。

23

riak

出力イベントをRiak分散キー/値ペアに保存するために使用されます。

24

s3

出力ログデータをAmazon Simple Storage Serviceに保存します。

25

sns

出力イベントをAmazonのSimple Notification Serviceに送信するために使用されます。

26

solr_http

Solrの出力ログデータにインデックスを付けて保存します。

27

sps

AWSのSimple Queue Serviceにイベントを出荷するために使用されます。

28

statsd

統計データをstatsdネットワークデーモンに送信するために使用されます。

29

stdout

コマンドプロンプトのようなCLIの標準出力に出力イベントを表示するために使用されます。

30

syslog

出力イベントをsyslogサーバーに出荷するために使用されます。

31

tcp

出力イベントをTCPソケットに送信するために使用されます。

32

udp

UDPを介して出力イベントをプッシュするために使用されます。

33

websocket

WebSocketプロトコルを介して出力イベントをプッシュするために使用されます。

34

xmpp

XMPPプロトコルを介して出力イベントをプッシュするために使用されます。

すべてのプラグインには固有の設定があり、プラグインでポート、パスなどの重要なフィールドを指定するのに役立ちます。 出力プラグインの設定について説明します。

エラスティックサーチ

Elasticsearch出力プラグインにより、Logstashは出力をElasticsearchエンジンの特定のクラスターに保存できます。 ELK Stackのパッケージに含まれているため、これはDevopsのエンドツーエンドソリューションを提供するため、これはユーザーの有名な選択肢の1つです。 次の表は、この出力プラグインの設定について説明しています。

Setting Name Default Value Description
action index It is used to define the action performed in Elasticsearch engine. Other values for this settings are delete, create, update, etc.
cacert It contains the path of file with .cer or .pem for server’s certificate validation.
codec “plain” It is used to encode the output logging data before sending it to the destination source.
doc_as_upset false This setting is used in case of update action. It creates a document in Elasticsearch engine, if the document id is not specified in output plugin.
document_type It is used to store the same type of events in the same document type. If it is not specified, then the event type is used for the same.
flush_size 500 This is used for improving the performance of bulk upload in Elasticsearch
hosts [“127.0.0.1”] It is an array of destination addresses for output logging data
idle_flush_time 1 It defines the time limit (second) between the two flushes, Logstash forces flush after the specified time limit in this setting
index "logstash-%\{+YYYY.MM.dd}" It is used to specify the index of Elasticsearch engine
manage_temlpate true It is used to apply the default template in Elasticsearch
parent nil It is used to specify the id of parent document in Elasticsearch
password It is used to authenticate the request to a secure cluster in Elasticsearch
path It is used to specify the HTTP path of Elasticsearch.
pipeline nil It is used to set the ingest pipeline, user wish to execute for an event
proxy It is used to specify HTTP proxy
retry_initial_interval 2 It is used to set the initial time interval (seconds) between bulk retries. It get double after each retry until it reach to retry_max_interval
retry_max_interval 64 It is used to set the maximum time interval for retry_initial_interval
retry_on_conflict 1 It is the number of retries by Elasticsearch to update a document
ssl To enable or disable SSL/TLS secured to Elasticsearch
template It contains the path of the customized template in Elasticsearch
template_name "logstash" This is used to name the template in Elasticsearch
timeout 60 It is the timeout for network requests to Elasticsearch
upsert “” It update the document or if the document_id does not exist, it creates a new document in Elasticsearch
user It contains the user to authenticate the Logstash request in secure Elasticsearch cluster

Eメール

Logstashが出力を生成するときに、電子メール出力プラグインを使用してユーザーに通知します。 次の表は、このプラグインの設定について説明しています。

Setting Name Default Value Description
address “localhost” It is the address of mail server
attachments [] It contains the names and locations of the attached files
body “” It contains the body of email and should be plain text
cc It contains the email addresses in comma separated manner for the cc of email
codec “plain” It is used to encode the output logging data before sending it to the destination source.
contenttype "text/html; charset = UTF-8" It is used to content-type of the email
debug false It is used to execute the mail relay in debug mode
domain "localhost" It is used to set the domain to send the email messages
from "[email protected]" It is used to specify the email address of the sender
htmlbody “” It is used to specify the body of email in html format
password It is used to authenticate with the mail server
port 25 It is used to define the port to communicate with the mail server
replyto It is used to specify the email id for reply-to field of email
subject “” It contains the subject line of the email
use_tls false Enable or disable TSL for the communication with the mail server
username Is contains the username for the authentication with the server
via “smtp” It defines the methods of sending email by Logstash

Http

この設定は、出力イベントをhttp経由で宛先に送信するために使用されます。 このプラグインには次の設定があります-

Setting Name Default Value Description
automatic_retries 1 It is used to set the number of http request retries by logstash
cacert It contains the path of file for server’s certificate validation
codec “plain” It is used to encode the output logging data before sending it to the destination source.
content_type I specifies the content type of http request to the destination server
cookies true It is used to enable or disable cookies
format "json" It is used to set the format of http request body
headers It contains the information of http header
http_method “” It is used to specify the http method used in the request by logstash and the values can be "put", "post", "patch", "delete", "get", "head"
request_timeout 60 It is used to authenticate with the mail server
url It is a required setting for this plugin to specify the http or https endpoint

標準

stdout出力プラグインは、コマンドラインインターフェイスの標準出力に出力イベントを書き込むために使用されます。 これは、WindowsのコマンドプロンプトとUNIXのターミナルです。 このプラグインには次の設定があります-

Setting Name Default Value Description
codec “plain” It is used to encode the output logging data before sending it to the destination source.
workers 1 It is used to specify number of workers for the output

statsd

これは、UDPを介して宛先バックエンドサービスにマトリックスデータを送信するために使用されるネットワークデーモンです。 これは、WindowsのコマンドプロンプトとUNIXのターミナルです。 このプラグインには次の設定があります-

Setting Name Default Value Description
codec “plain” It is used to encode the output logging data before sending it to the destination source.
count \{} It is used to define the count to be used in metrics
decrement [] It is used to specify the decrement metric names
host “localhost” It contains the address of statsd server
increment [] It is used to specify the increment metric names
port 8125 It contains the port of statsd server
sample_rate 1 It is used specify the sample rate of metric
sender “%{host}” It specifies the name of the sender
set \{} It is used to specify a set metric
timing \{} It is used to specify a timing metric
workers 1 It is used to specify number of workers for the output

フィルタープラグイン

Logstashは、入力ログを解析し、より構造化されたクエリしやすい形式に変換するためのさまざまなフィルタープラグインをサポートしています。

フィルタプラグインを使用するための構文は次のとおりです-

filter {
   Plugin name {
      Setting 1……
      Setting 2……..
   }
}

次のコマンドを使用して、フィルタプラグインをダウンロードできます-

>logstash-plugin install logstash-filter-<plugin name>

Logstashプラグインユーティリティは、Logstashインストールディレクトリのbinフォルダーにあります。 次の表に、Logstashが提供する出力プラグインを示します。

Sr.No. Plugin Name & Description
1

aggregate

このプラグインは、同じタイプのさまざまなイベントからデータを収集または集約し、最終イベントで処理します

2

alter

ユーザーがログイベントのフィールドを変更できるようにします。

3

anonymize

フィールドの値を一貫したハッシュに置き換えるために使用されます

4

cipher

出力イベントを宛先ソースに保存する前に暗号化するために使用されます

5

clone

Logstashで出力イベントの複製を作成するために使用されます

6

collate

異なるログのイベントを時間またはカウントでマージします

7

csv

このプラグインは、セパレータに従って入力ログからデータを解析します

8

date

イベントのフィールドから日付を解析し、イベントのタイムスタンプとして設定します

9

dissect

このプラグインは、ユーザーが非構造化データからフィールドを抽出するのに役立ち、grokフィルターがそれらを簡単に正しく解析できるようにします

10

drop

これは、同じタイプまたは他の類似のすべてのイベントをドロップするために使用されます

11

elapsed

開始イベントと終了イベントの間の時間を計算するために使用されます

12

Elasticsearch

Elasticsearchに存在する以前のログイベントのフィールドをLogstashの現在のフィールドにコピーするために使用されます

13

extractnumbers

ログイベントの文字列から数値を抽出するために使用されます

14

geoip

ログイベントに存在するIPの場所の緯度と経度を含むフィールドをイベントに追加します

15

grok

イベントを解析してフィールドを取得するために一般的に使用されるフィルタープラグインです

16

i18n

ログイベントのフィールドから特殊文字を削除します

17

json

イベントまたはイベントの特定のフィールドで構造化されたJsonオブジェクトを作成するために使用されます

18

kv

このプラグインは、ロギングデータのキーと値のペアをペアリングするのに役立ちます

19

metrics

各イベントの継続時間のカウントなどのメトリックを集約するために使用されます

20

multiline

また、一般的に使用されるフィルタープラグインの1つであり、複数行のログデータを単一のイベントに変換する場合に役立ちます。

21

mutate

このプラグインは、イベントのフィールドの名前変更、削除、置換、変更に使用されます

22

range

これは、イベント内のフィールドの数値を、予想される範囲および範囲内の文字列の長さと照合するために使用されていました。

23

ruby

任意のRubyコードを実行するために使用されます

24

sleep

これにより、Logstashは指定された時間だけスリープします

25

split

イベントのフィールドを分割し、そのイベントのクローンにすべての分割値を配置するために使用されます

26

xml

ログに存在するXMLデータを解析してイベントを作成するために使用されます

コーデックプラグイン

コーデックプラグインは、入力または出力プラグインの一部にすることができます。 これらのプラグインは、ロギングデータの表示を変更またはフォーマットするために使用されます。 Logstashは複数のコーデックプラグインを提供し、それらは次のとおりです-

Sr.No. Plugin Name & Description
1

avro

このプラグインは、Logstashイベントをシリアル化してavroデータにエンコードするか、またはavroレコードをLogstashイベントにデコードします

2

cloudfront

このプラグインは、AWSクラウドフロントからエンコードされたデータを読み取ります

3

cloudtrail

このプラグインは、AWS cloudtrailからデータを読み取るために使用されます

4

collectd

これは、UDP経由で収集と呼ばれるバイナリプロトコルからデータを読み取ります

5

compress_spooler

Logstashのログイベントをスプールバッチに圧縮するために使用されます

6

dots

これは、すべてのイベントにドットを標準出力に設定することにより、パフォーマンスの追跡に使用されます

7

es_bulk

これは、ElasticsearchからのバルクデータをElasticsearchメタデータを含むLogstashイベントに変換するために使用されます

8

graphite

このコーデックは、データをグラファイトからイベントに読み取り、イベントをグラファイト形式のレコードに変更します

9

gzip_lines

このプラグインは、gzipでエンコードされたデータを処理するために使用されます

10

json

これは、Json配列の単一の要素を単一のLogstashイベントに変換するために使用されます

11

json_lines

改行区切り文字を使用してJSONデータを処理するために使用されます

12

line

プラグインは、単一のライブでイベントを読み書きします。つまり、改行区切り文字の後に新しいイベントがあります。

13

multiline

複数行のロギングデータを単一のイベントに変換するために使用されます

14

netflow

このプラグインは、nertflow v5/v9データをlogstashイベントに変換するために使用されます

15

nmap

nmapの結果データをXML形式に解析します

16

plain

これは、区切り文字なしでテキストを読み取ります

17

rubydebug

このプラグインは、Rubyの素晴らしい印刷ライブラリを使用して出力Logstashイベントを書き込みます

独自のプラグインを構築する

Logstashで独自のプラグインを作成することもできます。これは要件に合っています。 Logstash-pluginユーティリティは、カスタムプラグインを作成するために使用されます。 ここでは、イベントにカスタムメッセージを追加するフィルタープラグインを作成します。

基本構造を生成する

ユーザーは、logstash-pluginユーティリティーの生成オプションを使用して必要なファイルを生成できます。または、GitHubでも使用できます。

>logstash-plugin generate --type filter --name myfilter --path c:/tpwork/logstash/lib

ここでは、 type オプションを使用して、プラグインが入力、出力、またはフィルターのいずれかであることを指定します。 この例では、 myfilter という名前のフィルタープラグインを作成しています。 pathオプションは、プラグインディレクトリを作成するパスを指定するために使用されます。 上記のコマンドを実行すると、ディレクトリ構造が作成されていることがわかります。

プラグインを開発する

プラグインのコードファイルは、プラグインディレクトリの \ lib \ logstash \ filters フォルダーにあります。 ファイル拡張子は .rb になります。

私たちの場合、コードファイルは次のパス内にありました-

C:\tpwork\logstash\lib\logstash-filter-myfilter\lib\logstash\filters\myfilter.rb

メッセージを-デフォルト⇒「こんにちは、finddevguides.comで学習しています」に変更して、ファイルを保存します。

プラグインをインストールする

このプラグインをインストールするには、LogstashのGemfileを変更する必要があります。 このファイルはLogstashのインストールディレクトリにあります。 この例では、 C:\ tpwork \ logstash にあります。 任意のテキストエディターを使用してこのファイルを編集し、次のテキストを追加します。

gem "logstash-filter-myfilter",:path => "C:/tpwork/logstash/lib/logstash-filter-myfilter"

上記のコマンドでは、プラグインの名前とインストール用のプラグインの場所を指定します。 次に、Logstash-pluginユーティリティーを実行して、このプラグインをインストールします。

>logstash-plugin install --no-verify

テスト

ここでは、前の例の1つに myfilter を追加しています-

*logstash.conf*

このLogstash構成ファイルには、grokフィルタープラグインの後のフィルターセクションにmyfilterが含まれています。

input {
   file {
      path => "C:/tpwork/logstash/bin/log/input1.log"
   }
}
filter {
   grok {
      match => [
         "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} -
            %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?" ]
   }
   myfilter{}
}
output {
   file {
      path => "C:/tpwork/logstash/bin/log/output1.log"
      codec => rubydebug
   }
}
  • logstashを実行*

次のコマンドを使用してLogstashを実行できます。

>logstash –f logsatsh.conf
*input.log*

次のコードブロックは、入力ログデータを示しています。

INFO - 48566 - TRANSACTION_START - start
*output.log*

次のコードブロックは、出力ログデータを示しています。

{
   "path" => "C:/tpwork/logstash/bin/log/input.log",
   "@timestamp" => 2017-01-07T06:25:25.484Z,
   "loglevel" => "INFO",
   "logger" => "TRANSACTION_END",
   "@version" => "1",
   "host" => "Dell-PC",
   "label" => "end",
   "message" => "Hi, You are learning this on finddevguides.com",
   "taskid" => "48566",
   "tags" => []
}

Logstashで公開する

開発者は、githubにアップロードし、Elasticsearch Companyによって定義された標準化された手順に従ってカスタムプラグインをLogstashに公開することもできます。

公開の詳細については、次のURLを参照してください-

https://www.elastic.co/guide/en/logstash/current/contributing-to-logstashl

Logstash-モニタリングAPI

Logstashは、パフォーマンスを監視するためのAPIを提供します。 これらの監視APIは、Logstashに関する実行時メトリックを抽出します。

ノード情報API

このAPIは、Logstashのノードに関する情報を取得するために使用されます。 OS、Logstashパイプライン、JVMの情報をJSON形式で返します。

次のURLを使用して、 get 要求をLogstashに送信することにより、情報を抽出できます-

GET http://localhost:9600/_node?pretty

応答

以下はNode Info APIの応答です。

{
   "host" : "Dell-PC",
   "version" : "5.0.1",
   "http_address" : "127.0.0.1:9600",

   "pipeline" : {
      "workers" : 4,
      "batch_size" : 125,
      "batch_delay" : 5,
      "config_reload_automatic" : false,
      "config_reload_interval" : 3
   },
   "os" : {
      "name" : "Windows 7",
      "arch" : "x86",
      "version" : "6.1",
      "available_processors" : 4
   },
   "jvm" : {
      "pid" : 312,
      "version" : "1.8.0_111",
      "vm_name" : "Java HotSpot(TM) Client VM",
      "vm_version" : "1.8.0_111",
      "vm_vendor" : "Oracle Corporation",
      "start_time_in_millis" : 1483770315412,

      "mem" : {
         "heap_init_in_bytes" : 16777216,
         "heap_max_in_bytes" : 1046937600,
         "non_heap_init_in_bytes" : 163840,
         "non_heap_max_in_bytes" : 0
      },
      "gc_collectors" : [ "ParNew", "ConcurrentMarkSweep" ]
   }
}

URLに名前を追加するだけで、Pipeline、OS、JVMの特定の情報を取得することもできます。

GET http://localhost:9600/_node/os?pretty
GET http://localhost:9600/_node/pipeline?pretty
GET http://localhost:9600/_node/jvm?pretty

プラグイン情報API

このAPIは、Logstashにインストールされているプラ​​グインに関する情報を取得するために使用されます。 この情報を取得するには、次のURLにgetリクエストを送信します-

GET http://localhost:9600/_node/plugins?pretty

応答

以下は、プラグイン情報APIの応答です。

{
   "host" : "Dell-PC",
   "version" : "5.0.1",
   "http_address" : "127.0.0.1:9600",
   "total" : 95,
   "plugins" : [ {
      "name" : "logstash-codec-collectd",
      "version" : "3.0.2"
   },
   {
      "name" : "logstash-codec-dots",
      "version" : "3.0.2"
   },
   {
      "name" : "logstash-codec-edn",
      "version" : "3.0.2"
   },
   {
      "name" : "logstash-codec-edn_lines",
      "version" : "3.0.2"
   },
   ............
}

Node Stats API

このAPIは、JSONオブジェクトのLogstash(メモリ、プロセス、JVM、パイプライン)の統計を抽出するために使用されます。 この情報を取得するには、次のURLにgetリクエストを送信します-

GET http://localhost:9600/_node/stats/?pretty
GET http://localhost:9600/_node/stats/process?pretty
GET http://localhost:9600/_node/stats/jvm?pretty
GET http://localhost:9600/_node/stats/pipeline?pretty

ホットスレッドAPI

このAPIは、Logstashのホットスレッドに関する情報を取得します。 ホットスレッドはJavaスレッドで、CPU使用率が高く、通常の実行時間よりも長く実行されます。 この情報を取得するには、次のURLにgetリクエストを送信します-

GET http://localhost:9600/_node/hot_threads?pretty

ユーザーは次のURLを使用して、より読みやすい形式で応答を取得できます。

GET http://localhost:9600/_node/hot_threads?human = true

Logstash-セキュリティと監視

この章では、Logstashのセキュリティと監視の側面について説明します。

モニタリング

Logstashは、実稼働環境でサーバーとサービスを監視するための非常に優れたツールです。 実稼働環境のアプリケーションは、アクセスログ、エラーログなどのさまざまな種類のログデータを生成します。 Logstashは、フィルタープラグインを使用して、エラー、アクセス、またはその他のイベントの数をカウントまたは分析できます。 この分析とカウントは、さまざまなサーバーとそのサービスの監視に使用できます。

Logstashは、 HTTP Poller のようなプラグインを提供して、Webサイトのステータス監視を監視します。 ここでは、ローカルApache Tomcatサーバーでホストされている mysite という名前のWebサイトを監視しています。

logstash.conf

この構成ファイルでは、間隔設定で指定された時間間隔後に、プラグインで指定されたサイトにアクセスするためにhttp_pollerプラグインが使用されます。 最後に、サイトのステータスを標準出力に書き込みます。

input {
   http_poller {
      urls => {
         site => "http://localhost:8080/mysite"
      }
      request_timeout => 20
      interval => 30
      metadata_target => "http_poller_metadata"
   }
}
output {
   if [http_poller_metadata][code] == 200 {
      stdout {
         codec => line{format => "%{http_poller_metadata[response_message]}"}
      }
   }
   if [http_poller_metadata][code] != 200 {
      stdout {
         codec => line{format => "down"}
      }
   }
}

logstashを実行する

次のコマンドでLogstashを実行できます。

>logstash –f logstash.conf

標準

サイトが稼働している場合、出力は次のようになります-

Ok

Tomcatの* Managerアプリ*を使用してサイトを停止すると、出力は次のように変わります-

down

セキュリティ

Logstashは、外部システムとの安全な通信のための多くの機能を提供し、認証メカニズムをサポートします。 すべてのLogstashプラグインは、HTTP接続を介した認証と暗号化をサポートしています。

HTTPプロトコルによるセキュリティ

ElasticsearchプラグインなどのLogstashが提供するさまざまなプラグインには、認証目的のユーザーやパスワードなどの設定があります。

elasticsearch {
   user => <username>
   password => <password>
}

もう1つの認証は、Elasticsearchの* PKI(公開キー基盤)*です。 開発者は、PKI認証を有効にするためにElasticsearch出力プラグインで2つの設定を定義する必要があります。

elasticsearch {
   keystore => <string_value>
   keystore_password => <password>
}

HTTPSプロトコルでは、開発者はSSL/TLSに認証局の証明書を使用できます。

elasticsearch {
   ssl => true
   cacert => <path to .pem file>
}

トランスポートプロトコルによるセキュリティ

Elasticsearchでトランスポートプロトコルを使用するには、ユーザーがプロトコル設定をtransportに設定する必要があります。 これにより、JSONオブジェクトの非整列化が回避され、効率が向上します。

基本認証は、Elasticsearch出力プロトコルのhttpプロトコルで実行されるものと同じです。

elasticsearch {
   protocol => “transport”
   user => <username>
   password => <password>
}

PKI認証では、Elasticsearch出力プロトコルの他の設定でSSLセットがtrueになる必要もあります-

elasticsearch {
   protocol => “transport”
   ssl => true
   keystore => <string_value>
   keystore_password => <password>
}

最後に、SSLセキュリティには、通信の他のセキュリティ方法よりも多くの設定が必要です。

elasticsearch {
   ssl => true
   ssl => true
   keystore => <string_value>
   keystore_password => <password>
   truststore =>
   truststore_password => <password>
}

Logstashのその他のセキュリティ上の利点

Logstashは、システムソースを入力して、サービス拒否攻撃などの攻撃を防ぐのに役立ちます。 ログの監視とそれらのログ内のさまざまなイベントの分析は、システム管理者が着信接続とエラーの変動を確認するのに役立ちます。 これらの分析は、サーバーで攻撃が発生しているかどうかを確認するのに役立ちます。

Elasticsearch Companyの他の製品( x-packfilebeat など)は、Logstashと安全に通信するための機能を提供します。