Loki
使用方法
API
要通过原始 HTTP API 将日志发送到 GreptimeDB,请使用以下信息:
- URL:
http{s}://<host>/v1/loki/api/v1/push - Headers:
GreptimeDB 支持 Loki Push API 的以下两种负载编码:
- Protobuf:发送符合 logproto.proto 定义、经过 Snappy 压缩的
PushRequest,并设置Content-Type: application/x-protobuf。 - JSON:发送 Loki JSON Push 请求体,并设置
Content-Type: application/json。
示例代码
Grafana Alloy 是一个供应商中立的 OpenTelemetry (OTel) Collector 发行版。Alloy 独特地结合了社区中最好的开源可观测性信号。
它提供了一个 Loki 导出器,可以用来将日志发送到 GreptimeDB。以下是一个配置示例:
loki.source.file "greptime" {
targets = [
{__path__ = "/tmp/foo.txt"},
]
forward_to = [loki.write.greptime_loki.receiver]
}
loki.write "greptime_loki" {
endpoint {
url = coalesce(sys.env("GREPTIME_SCHEME"), "http") + "://" +
coalesce(sys.env("GREPTIME_HOST"), "greptimedb") + ":" +
coalesce(sys.env("GREPTIME_PORT"), "4000") + "/v1/loki/api/v1/push"
headers = {
"x-greptime-db-name" = coalesce(sys.env("GREPTIME_DB"), "public"),
"x-greptime-log-table-name" = coalesce(sys.env("GREPTIME_LOG_TABLE_NAME"), "loki_demo_logs"),
}
}
external_labels = {
"job" = "greptime",
"from" = "alloy",
}
}
此配置从文件 /tmp/foo.txt 读取日志并将其发送到 GreptimeDB。日志存储在表 loki_demo_logs 中,并带有 label job 和 from。
更多信息,请参考 Grafana Alloy loki.write 文档。
你可以运行以下命令来检查表中的数据:
SELECT * FROM loki_demo_logs;
+----------------------------+------------------------+---------------------+--------------+-------+----------+
| greptime_timestamp | line | structured_metadata | filename | from | job |
+----------------------------+------------------------+---------------------+--------------+-------+----------+
| 2024-11-25 11:02:31.256251 | Greptime is very cool! | {} | /tmp/foo.txt | alloy | greptime |
+----------------------------+------------------------+---------------------+--------------+-------+----------+
1 row in set (0.01 sec)
数据模型
Loki 日志数据模型根据以下规则映射到 GreptimeDB 数据模型:
没有 label 的默认表结构:
DESC loki_demo_logs;
+---------------------+---------------------+------+------+---------+---------------+
| Column | Type | Key | Null | Default | Semantic Type |
+---------------------+---------------------+------+------+---------+---------------+
| greptime_timestamp | TimestampNanosecond | PRI | NO | | TIMESTAMP |
| line | String | | YES | | FIELD |
| structured_metadata | Json | | YES | | FIELD |
+---------------------+---------------------+------+------+---------+---------------+
3 rows in set (0.00 sec)
greptime_timestamp: 日志条目的时间戳line: 日志消息内容structured_metadata: 日志条目的结构化元数据,JSON 格式
如果 Loki 请求数据中含有 label,它们将作为 tag 添加到表结构中(如上例中的 job 和 from)。
重要说明:
- 所有 label 都被视为字符串类型的 tag
- 请不要尝试使用 SQL 预先创建表来指定 tag 列,这会导致类型不匹配和写入失败