Loki日誌全鏈路實戰:從收集到告警的完整指南

新鈦雲服已累計為您分享836篇技術乾貨
01
為什麼選擇Loki ?

傳統日誌系統的痛點

  • 資源消耗高:ELK(Elasticsearch)需要為全文檢索建立複雜索引,儲存成本飆升,官方資料是通常可以將資料壓縮20%~30%,實測下來在某些場景下可以達到50%,使用DEFLATE壓縮演算法,最低可以降低超過70%
  • 雲原生適配差:Kubernetes動態環境下的日誌標籤管理困難

Loki的核心優勢

  • 輕量級設計:僅索引元資料(標籤),有近10倍的壓縮比,5G資料輸入儲存實際增長0.5G。
  • 無縫整合:原生支援Prometheus生態,原生整合grafana,支援叢集本身監控告警和日誌監控告警。
  • 動態標籤:完美適配Kubernetes Pod/Node等動態資源標籤
02
Loki架構解析

核心元件與資料流

Loki則採用了分散式架構,將日誌資料儲存在多個節點上,Promtail進行日誌收集,視覺化依賴於Grafana。

關鍵概念解析

03
部 署

環境準備

  • 硬體建議:
    • 生產環境:至少3節點叢集(每個節點4核8GB+)
    • 儲存:優先選擇SSD + S3相容儲存(MinIO)
  • 版本選擇:
推薦使用v2.8+版本helm repo add grafana https://grafana.github.io/helm-chartshelm repo update

Kubernetes叢集部署

使用Helm部署Loki Stack(包含Promtail)helm upgrade --install loki grafana/loki-stack \  --set promtail.enabled=true \  --set loki.persistence.enabled=true \  --set loki.persistence.size=100Gi

Promtail配置示例

#promtail-config.yamlserver:  http_listen_port: 9080positions:  filename: /tmp/positions.yamlclients:url: http://loki:3100/loki/api/v1/pushscrape_configs:job_name: kuberneteskubernetes_sd_configs:role: pod  pipeline_stages:docker: {}  relabel_configs:source_labels: [__meta_kubernetes_pod_label_app]  target_label: app
04
告警整合

grafana告警規則配置

05
效能最佳化與分析實踐
儲存最佳化技巧
#loki-config.yaml 最佳化片段schema_config:  configs:    - from: 2023-01-01      store: boltdb-shipper      object_store: s3      schema: v11      index:        prefix: index_        period: 24hchunk_store_config:  max_look_back_period: 720h # 日誌保留30天

日誌查詢和分析

  1. 首先,指定 查詢檔案 filename="/usr/local/nginx/logs/loki-error.log"
  2. 然後,透過json的方式
  3. 最後,設定條件選擇,比如status=500、server_name=test.com

查詢加速策略

  1. 預過濾標籤
#先透過精確標籤縮小範圍{cluster="aws", pod=~"frontend-.+"} |= "timeout"
  1. 避免全文字掃描:優先使用|=(包含)而非|~(正則)
06
真實場景案例

案例1:nginx5xx日誌收集

重新編譯nginx

#上傳安裝包nginx-1.25.3.tar.gz、ngx_http_geoip2_module-3.4.tar.gz、libmaxminddb-1.9.1.tar.gz、GeoLite2-City.mmdb、GeoLite2-Country.mmdb#nginx重新編譯./configure --prefix=/usr/local/nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-dynamic-module=/root/nginx/ngx_http_geoip2_module-3.4

修改日誌格式

load_module modules/ngx_http_geoip2_module.so;#修改日誌格式  log_format json_analytics escape=json '{'                    '"msec""$msec", '                     '"connection""$connection", '                    '"connection_requests""$connection_requests", '                     '"http_referer""$http_referer", '                    '"http_user_agent""$http_user_agent", '                     '"request_method""$request_method", '                    '"server_protocol""$server_protocol", '                    '"status""$status", '                    '"pipe""$pipe", '                     '"server_name""$server_name", '                    '"request_time""$request_time", '                     '"gzip_ratio""$gzip_ratio", '                    '"http_cf_ray""$http_cf_ray",'                    '"geoip_country_code""$geoip2_data_country_code",'                    '"geoip2_city_name_en""$geoip2_city_name_en", '                    '"geoip2_city_name_cn""$geoip2_city_name_cn", '                    '"geoip2_longitude""$geoip2_longitude", '                    '"geoip2_latitude""$geoip2_latitude"'                    '}';    map $http_x_forwarded_for$real_ip {default"";"~^(?P<ip>\d+\.\d+\.\d+\.\d+)"$ip;"~^(?P<ip>\d+\.\d+\.\d+\.\d+),.*"$ip;    }#指定日誌的位置,會放在nginx目錄下    map $status$log_path {~^4/logs/loki-error.log;~^5/logs/loki-error.log;default/logs/access.log;    }    geoip2 /usr/local/nginx/modules/GeoLite2-Country.mmdb {        auto_reload 5m;$geoip2_metadata_country_build metadata build_epoch;$geoip2_data_country_code source=$real_ip country iso_code;$geoip2_data_country_name country names zh-CN;    }    geoip2 /usr/local/nginx/modules/GeoLite2-City.mmdb {$geoip2_city_name_en source=$real_ip city names en;$geoip2_city_name_cn source=$real_ip city names zh-CN;$geoip2_longitude source=$real_ip location longitude ;$geoip2_latitude source=$real_ip location latitude ;    }    fastcgi_param COUNTRY_CODE$geoip2_data_country_code;    fastcgi_param COUNTRY_NAME$geoip2_data_country_name;    fastcgi_param CITY_NAME$geoip2_city_name_cn;    check interval=3000 rise=2 fall=5 timeout=1000 type=tcp;    check_http_send "HEAD /health/check/status HTTP/1.0\r\n\r\n";    check_http_expect_alive http_2xx http_3xx;

配置promtail收集

cat << EOF >> /data/promtail/config.yamlserver:  http_listen_port: 9080  grpc_listen_port: 0positions:  filename: /tmp/positions.yamlclients:url: http://192.168.119.191:3100/loki/api/v1/pushscrape_configs:job_name: nginxstatic_configs:targets:localhost    labels:    job: nginx    host: $host    agent: promtail    path    : /usr/local/nginx/logs/loki-error.logEOF

結合grafana呈現效果

案例2:資料庫慢查詢收集

配置promtail收集

cat config.yaml server:  http_listen_port: 9080  grpc_listen_port: 0positions:  filename: /tmp/positions.yamlclients:url: http://192.168.119.191:3100/loki/api/v1/pushscrape_configs:- job_name: mysql-slowlogs      static_configs:- labels:            instance: usa4-rds03-slave            projectname: chat            job: mysql            __path__: /database/mysql/1266/mysql-slow.log      pipeline_stages:- multiline:              firstline: '#\sTime:.'- regex:*              expression: '#\s*Time:\s*(?P<timestamp>.*)\n#\s*User@Host:\s*(?P<user>[^\[]+).*@\s*(?P<host>.*]).***Id:\s***(?P<id>\d+)\n#\s*Query_time:\s*(?P<query_time>\d+\.\d+)\s*Lock_time:\s*(?P<lock_time>\d+\.\d+)\s*Rows_sent:\s*(?P<rows_sent>\d+)\s*Rows_examined:\s*(?P<rows_examined>\d+)\n(?P<query>(?s:.*))$'- labels:            timestamp:            user:            host:            id:            query_time:            lock_time:            rows_sent:            rows_examined:            query:- drop:            expression: "^ *$"            drop_counter_reason: "drop empty lines"

結合grafana呈現效果

07
總 結
總體而言,Loki相對輕量級,具有較高的可擴充套件性和簡化的儲存架構,但需要額外的元件,Loki使用的是自己的查詢語言LokiQL,有一定的學習曲線。若是資料量適中,資料屬於時序類,如應用程式日誌和基礎設施指標,並且應用使用kubernetes Pod形式部署,則選擇Loki比較合適。
Loki正在成為雲原生時代日誌管理的標準解決方案,其與以下技術的整合值得關注:
  • OpenTelemetry:統一日誌、指標、追蹤的採集標準
  • WALWrite-Ahead Logging:提升高吞吐場景下的可靠性
  • 邊緣計算:輕量級特性適合IoT裝置日誌收集
如有相關問題,請在文章後面給小編留言,小編安排作者第一時間和您聯絡,為您答疑解惑。

附錄

參考文章:
https://www.ctyun.cn/developer/article/418138645577797
http://cloud.tencent.com/developer/article/2241079
    推薦閱讀   

    推薦影片    

相關文章