콘텐츠로 이동

Fluent Bit으로 Integration Trace Log Pipeline 만들기

Interactive Diagram

새 탭 ↗

Integration log는 application이 출력한 문자열에서 시작하지만 운영자가 필요한 것은 검색 가능한 event document다. Fluent Bit은 node 또는 pod의 log 파일을 읽고, 정규식으로 Trace 필드를 추출하고, 필요한 event만 통과시킨 뒤 OpenSearch에 전송하는 경량 pipeline을 구성한다.

이 글은 GUID, UUID, HOP, SEQ를 포함한 anonymized log를 대상으로 Tail → Parser → Filter → Output 흐름을 설계한다. 수집기는 business transaction을 재처리하지 않는다. 따라서 log pipeline의 전달 보장과 업무 메시지의 전달 보장을 별개로 설계해야 한다.

PlantUML Diagram

Tail input은 파일 offset을 position DB에 저장한다. pod가 재시작해도 이미 읽은 위치부터 계속 읽으려면 position DB와 filesystem buffering을 ephemeral memory에만 두지 않아야 한다.

[INPUT]
Name tail
Path /var/log/integration/plain/*.log
Tag integration.plain.*
Parser runtime-line
Skip_Long_Lines On
Buffer_Chunk_Size 64K
Buffer_Max_Size 8M
storage.type filesystem
storage.pause_on_chunks_overlimit On
[INPUT]
Name tail
Path /var/log/integration/json/*.log
Tag integration.json.*
Skip_Long_Lines On
Buffer_Chunk_Size 64K
Buffer_Max_Size 8M
storage.type filesystem
storage.pause_on_chunks_overlimit On

Skip_Long_Lines가 실제로 결정하는 것

섹션 제목: “Skip_Long_Lines가 실제로 결정하는 것”

이름만 보면 “긴 줄을 버릴지” 정하는 option 같지만 영향 범위는 훨씬 넓다. tail plugin은 한 줄이 Buffer_Max_Size를 넘으면 그 줄을 온전히 조립할 수 없다고 판단한다. 이때 기본값인 Skip_Long_Lines Off는 해당 파일 전체의 감시를 중단한다. 즉 긴 stack trace 한 줄 때문에 그 파일에 이후 기록되는 모든 log를 잃는다. On은 길이를 초과한 그 줄만 건너뛰고 다음 줄부터 계속 읽는다.

따라서 이 값은 “긴 줄을 지킬 것인가”가 아니라 긴 줄 하나를 잃을 것인가, 파일 하나를 통째로 잃을 것인가의 trade-off다. 운영 pipeline에서는 거의 언제나 On이 맞다. 긴 줄 자체를 보존하고 싶다면 Off로 되돌리는 것이 아니라 Buffer_Max_Size를 실제 최대 line 길이보다 넉넉하게 올려서 해결한다. 그리고 건너뛴 line이 조용히 사라지지 않도록 skip counter를 Metrics로 노출한다.

rotation 시 inode와 파일명을 함께 고려하고, 여러 pod의 동일 tag가 충돌하지 않도록 Metadata를 추가한다.

application이 JSON을 출력할 수 있으면 JSON parser를 우선한다. legacy plain log라면 고정 prefix와 Trace field를 정규식 named capture로 분리한다.

[PARSER]
Name runtime-line
Format regex
Regex ^(?<time>[^ ]+) (?<logLevel>[^ ]+) (?<appName>[^ ]+) (?<eventType>[^ ]+) (?<guid>[^ ]+) (?<uuid>[^ ]+) (?<hop>[0-9]+) (?<seq>[0-9]+) (?<interfaceId>[^ ]+) (?<statusCode>[^ ]+) (?<message>.*)$
Time_Key time
Time_Format %Y-%m-%dT%H:%M:%S.%LZ
[PARSER]
Name runtime-json
Format json
Time_Key time
Time_Format %Y-%m-%dT%H:%M:%S.%LZ

runtime-line이 만드는 필드 이름을 정확히 기억해야 한다. named capture가 (?<message>.*)이므로 본문은 log가 아니라 message에 담긴다. 이후 filter에서 key 이름을 틀리면 filter는 아무 일도 하지 않고 조용히 통과한다.

Time_Key time은 정규식이 추출한 time 필드를 record의 timestamp로 승격시킨다. 이 값이 뒤에서 OpenSearch output의 index 이름과 @timestamp를 결정한다.

정규식 parser는 정상 log와 stack trace가 여러 줄로 나뉘는 경우를 구분해야 한다. multiline rule을 잘못 적용하면 서로 다른 request의 line이 합쳐진다. 가능하면 application에서 exception을 one-line JSON 또는 명확한 multiline prefix로 출력한다.

Parser가 실패해도 원문을 버리지 않고 parse_error=true를 추가해 quarantine index로 보낼 수 있다. Trace dashboard에 필요한 event type만 기본 index에 보내고, 운영 분석용 debug event는 별도 route로 분리한다.

아래 첫 번째 filter는 정규식 INPUT에 겹쳐 쓰는 설정이 아니라 JSON 형식으로 출력되는 log만 처리하는 분기다. 그래서 Match가 integration.json.*이고, JSON INPUT은 parser를 지정하지 않은 채 raw line을 넘긴다. 이때 tail이 만드는 기본 key는 log이므로 Key_Name log가 맞다. 반대로 정규식 INPUT을 거친 record에 같은 filter를 적용하려면 Key_Name은 반드시 message여야 한다. 두 경로를 tag로 갈라 두면 key 이름을 헷갈릴 여지가 사라진다.

[FILTER]
Name parser
Match integration.json.*
Key_Name log
Parser runtime-json
Reserve_Data True
Preserve_Key False
[FILTER]
Name grep
Match integration.*
Regex eventType ^(IFST|IFEN|TXST|TXEN|SEND|RECV|ERR)$

Reserve_Data는 원본이 유용한 동안 유지할 수 있지만, 원문에 secret이 있으면 위험하다. header, token, cookie, 개인 식별 정보와 같은 민감정보는 application 단계에서 먼저 제거하고, collector에는 field-level allowlist와 최대 message 길이를 둔다. raw payload를 저장해야 한다면 검색 index가 아닌 접근 통제된 별도 저장소에 보관한다.

[OUTPUT]
Name opensearch
Match integration.*
Host search.example.invalid
Port 443
tls On
tls.verify On
Logstash_Format On
Logstash_Prefix integration-trace
Suppress_Type_Name On
storage.total_limit_size 1G

예시 host는 문서용 placeholder다. 실제 credential은 ConfigMap이나 설정 파일에 직접 넣지 말고 secret injection과 least privilege 계정을 사용한다. TLS verification을 끄면 수집기와 검색 cluster 사이의 log 내용과 인증 정보를 노출할 수 있다.

filesystem storage에서 backpressure를 결정하는 key

섹션 제목: “filesystem storage에서 backpressure를 결정하는 key”

흔한 실수는 Mem_Buf_Limit과 storage.type filesystem을 함께 적는 것이다. 두 값은 같은 계층에서 동작하지 않는다. Mem_Buf_Limit은 memory buffering(storage.type memory)일 때만 의미가 있고, filesystem storage로 전환하는 순간 무시된다. 그래서 위 INPUT 예시에는 Mem_Buf_Limit이 없다. filesystem storage에서 input의 backpressure를 실제로 결정하는 key는 다음 세 가지다.

  • storage.max_chunks_up: memory에 동시에 올려둘 수 있는 chunk 수의 상한이다. 이 값을 넘어서면 나머지 chunk는 disk에만 남는다.
  • storage.pause_on_chunks_overlimit: On이면 상한에 도달했을 때 해당 input을 일시 정지시켜 파일 읽기를 늦춘다. Off면 input은 계속 읽고 chunk는 disk에 쌓인다.
  • storage.total_limit_size: output별 disk queue의 상한이다. 가득 차면 가장 오래된 chunk부터 버린다.

정리하면 pause_on_chunks_overlimit On은 “읽기를 늦춰서라도 log를 지킨다”는 선택이고, Off와 storage.total_limit_size 조합은 “계속 읽되 오래된 것부터 버린다”는 선택이다. 어느 쪽도 무한 queue가 아니므로 정책을 명시적으로 정해야 한다. 업무 응답 latency를 보호하려면 collector가 application stdout을 block하지 않도록 하고, drop count·retry count·chunk 사용량을 Metrics로 노출한다.

guid, interfaceId, eventType, statusCode는 keyword, timestamp는 date, hop과 seq는 integer로 mapping한다. message는 full-text가 필요할 때만 text로 두고, dashboard filter에 사용할 field를 message 문자열 안에서 다시 검색하지 않는다. 이 규칙은 문장이 아니라 index template으로 고정해야 한다.

{
"index_patterns": ["integration-trace-*"],
"priority": 100,
"template": {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"refresh_interval": "5s"
},
"mappings": {
"dynamic_templates": [
{
"strings_as_keyword": {
"match_mapping_type": "string",
"mapping": { "type": "keyword", "ignore_above": 256 }
}
}
],
"properties": {
"@timestamp": { "type": "date" },
"time": { "type": "date" },
"guid": { "type": "keyword" },
"uuid": { "type": "keyword" },
"interfaceId": { "type": "keyword" },
"eventType": { "type": "keyword" },
"statusCode": { "type": "keyword" },
"appName": { "type": "keyword" },
"logLevel": { "type": "keyword" },
"hop": { "type": "integer" },
"seq": { "type": "integer" },
"message": { "type": "text" }
}
}
}
}

dynamic_templates는 예상하지 못한 문자열 field가 들어와도 text와 keyword 이중 mapping으로 번지지 않게 막는다. field 목록이 완전히 고정되어 있다면 더 강한 선택으로 dynamic: strict를 쓴다.

{
"mappings": {
"dynamic": "strict",
"properties": {
"guid": { "type": "keyword" },
"interfaceId": { "type": "keyword" },
"eventType": { "type": "keyword" },
"statusCode": { "type": "keyword" },
"hop": { "type": "integer" },
"seq": { "type": "integer" },
"message": { "type": "text" }
}
}
}

strict는 schema에 없는 field가 들어오면 document 자체를 거부한다. mapping explosion은 확실히 막지만 application이 field를 추가하는 순간 수집이 끊긴다. 그래서 rejection 수를 Metrics로 관측하고, template 배포를 application 배포보다 먼저 수행하는 Schedule을 지켜야 한다.

Index는 날짜 기반 alias로 교체하고 retention을 적용한다. OpenSearch에서는 ISM policy로 rollover와 삭제를 자동화한다.

{
"policy": {
"description": "integration trace rollover and retention",
"default_state": "hot",
"ism_template": [
{ "index_patterns": ["integration-trace-*"], "priority": 100 }
],
"states": [
{
"name": "hot",
"actions": [
{ "rollover": { "min_primary_shard_size": "30gb", "min_index_age": "1d" } }
],
"transitions": [{ "state_name": "warm", "conditions": { "min_index_age": "7d" } }]
},
{
"name": "warm",
"actions": [
{ "read_only": {} },
{ "force_merge": { "max_num_segments": 1 } }
],
"transitions": [{ "state_name": "delete", "conditions": { "min_index_age": "90d" } }]
},
{
"name": "delete",
"actions": [{ "delete": {} }],
"transitions": []
}
]
}
}

Trace detail은 guid와 시간 범위로 조회하며, dashboard는 interfaceId와 시간 bucket aggregation을 사용한다. rollover 지연이나 ISM 실패는 곧바로 조회 누락으로 이어지므로 index 수와 policy 실패 상태를 Alert 대상으로 둔다. Data Stream, Hot/Cold tier, StatefulSet Storage, rollover와 snapshot 복구의 전체 경계는 Kubernetes에서 OpenSearch Hot/Cold Storage와 Index Lifecycle 설계하기에서 이어서 다룬다.

  1. 안전한 가상 log 한 줄을 parser에 넣고 field가 정확히 추출되는지 확인한다.
  2. malformed line, Buffer_Max_Size를 넘는 stack trace, newline이 포함된 JSON을 각각 시험한다. 특히 긴 줄 이후에도 같은 파일의 다음 줄이 계속 수집되는지 확인한다.
  3. Filter가 정상 event와 ERR를 보존하고 민감 field를 제거하는지 확인한다.
  4. output 장애 중 chunk가 증가하고 복구 후 flush되는지, storage.total_limit_size 도달 시 정책대로 동작하는지 확인한다.
  5. 중복 수집 가능성을 고려해 uuid 또는 (guid, uuid)를 document id 후보로 검토한다. at-least-once 수집에서는 중복이 없다고 가정하지 않아야 한다.

Tail은 offset과 파일 수집, Parser는 schema 추출, Filter는 범위와 redaction, Output은 전달·buffer·TLS를 책임진다. 각 단계를 분리하면 log format 변경과 검색 cluster 장애를 독립적으로 운영할 수 있다. 무엇보다 수집 성공을 업무 처리 성공으로 해석하지 않고, pipeline 자체의 loss와 backpressure를 관측해야 한다.