在 Java 应用里运用 ELK(Elasticsearch、Logstash、Kibana)技术栈,能够实现日志的集中化管理、高效搜索以及直观可视化。下面将从基础概念入手,逐步深入讲解其使用方法。
ELK 技术栈由三款开源工具构成:
要在 Java 项目中使用 ELK,首先需要添加相应的依赖。以下是在 Maven 项目中添加 Elasticsearch 客户端依赖的代码:
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.17.3
下面的代码展示了如何创建一个 Elasticsearch 的高级 REST 客户端:
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticsearchConfig {
public static RestHighLevelClient createClient() {
return new RestHighLevelClient(
RestClient.builder(
new org.apache.http.HttpHost("localhost", 9200, "http")));
}
}
使用 Logback 和 Logstash 实现日志收集的配置如下:
localhost:5000
Logstash 的配置文件logstash.conf
示例如下:
input {
tcp {
port => 5000
codec => json_lines
}
}
output {
elasticsearch {
hosts => ["http://localhost:9200"]
index => "java-app-logs-%{+YYYY.MM.dd}"
}
}
在 Logstash 配置中添加过滤器,能够实现对日志的增强处理。以下是一个添加了过滤器的 Logstash 配置示例:
filter {
if [message] =~ /ERROR/ {
mutate {
add_tag => ["error"]
}
}
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:message}" }
}
date {
match => [ "timestamp", "yyyy-MM-dd HH:mm:ss" ]
}
}
通过 Micrometer 可以将应用指标发送到 Elasticsearch,代码示例如下:
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsConfig {
@Bean
MeterRegistryCustomizer metricsCommonTags() {
return registry -> registry.config().commonTags("application", "my-java-app");
}
}
Elasticsearch 的elasticsearch.yml
集群配置示例如下:
cluster.name: my-application
node.name: node-1
network.host: 0.0.0.0
http.port: 9200
discovery.seed_hosts: ["host1", "host2"]
cluster.initial_master_nodes: ["node-1", "node-2"]
为了优化 Elasticsearch 的性能,可以进行以下配置调整:
indices.memory.index_buffer_size: 30%
search.max_buckets: 100000
bootstrap.memory_lock: true
保障 ELK 安全的配置示例如下:
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: elastic-certificates.p12
在 Kibana 中创建可视化图表的 DSL 示例:
{
"aggs": {
"by_level": {
"terms": {
"field": "level.keyword",
"size": 10
},
"aggs": {
"by_hour": {
"date_histogram": {
"field": "@timestamp",
"calendar_interval": "hour"
}
}
}
}
},
"size": 0
}
在 Spring Boot 项目中使用 ELK 的自动配置,需要添加以下依赖:
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-data-elasticsearch
application.properties
配置示例:
spring.elasticsearch.rest.uris=http://localhost:9200
management.metrics.export.elastic.enabled=true
management.metrics.export.elastic.host=http://localhost:9200
/var/log/elasticsearch/
GET /_cluster/health
GET /_nodes/stats/indices/search
通过上述内容,我们全面了解了 ELK 在 Java 应用中的使用方法:
通过合理运用 ELK 技术栈,可以显著提升 Java 应用的可观测性和运维效率