菜单
开源软件

使用 Grafana Alloy 监控本地文件中的日志

日志文件记录系统、应用程序或网络中的事件、活动和使用模式。这些文件对于监控、故障排除和理解系统行为至关重要。借助 Alloy,您可以收集日志,将其转发到 Grafana 技术栈,并创建仪表盘来监控您的系统行为。

alloy-scenarios 仓库包含 Alloy 部署的完整示例。克隆该仓库并使用这些示例来了解 Alloy 如何收集、处理和导出遥测信号。

在此示例场景中,Alloy 从本地文件收集日志,并将其转发到 Loki 目的地。

开始之前

确保您已安装以下工具

注意

您需要管理员权限才能运行 docker 命令。

克隆并部署示例

按照以下步骤克隆 scenarios 仓库并部署监控示例

  1. 克隆 Alloy scenarios 仓库。

    shell
    git clone https://github.com/grafana/alloy-scenarios.git
  2. 启动 Docker 以部署 Grafana 技术栈。

    shell
    cd alloy-scenarios/logs-file
    docker compose up -d

    验证 Docker 容器的状态

    shell
    docker ps
  3. (可选)探索完此示例后,停止 Docker 以关闭 Grafana 技术栈。

    shell
    docker compose down

监控和可视化您的数据

使用 Grafana 监控您的部署健康状况并可视化您的数据。

监控 Alloy

要监控您的 Alloy 部署健康状况,请打开浏览器并访问 https://:12345

有关 Alloy UI 的更多信息,请参阅调试 Grafana Alloy

可视化您的数据

要使用 Grafana Logs Drilldown,请打开浏览器并访问 https://:3000/a/grafana-lokiexplore-app

要创建用于可视化指标和日志的仪表盘,请打开浏览器并访问 https://:3000/dashboards

理解 Alloy 配置

此示例使用 config.alloy 文件来配置用于日志记录的 Alloy 组件。您可以在克隆的仓库中的 alloy-scenarios/logs-file/ 找到此文件。

配置中包含 livedebugging,用于将实时数据流式传输到 Alloy UI。

配置 livedebugging

livedebugging 将您的组件中的实时数据直接流式传输到 Alloy UI。有关此功能的更多详细信息,请参阅故障排除文档

livedebugging

默认情况下,livedebugging 是禁用的。通过 livedebugging 配置块明确启用它,以使调试数据在 Alloy UI 中可见。

alloy
livedebugging {
  enabled = true
}

配置日志记录

此示例中的日志记录配置需要以下三个组件

  • local.file_match
  • loki.source.file
  • loki.write

local.file_match

local.file_match 组件使用 glob 模式发现本地文件系统上的文件。在此示例中,该组件需要以下参数

  • path_targets: 要扩展的目标。在 __path__ 键上查找 glob 模式。
  • sync_period: 同步文件系统和目标的频率。
alloy
local.file_match "local_files" {
    path_targets = [{"__path__" = "/temp/logs/*.log", "job" = "python", "hostname" = constants.hostname}]
    sync_period  = "5s"
}

loki.source.file

loki.source.file 组件从文件中读取日志条目并将其转发给其他 Loki 组件。在此示例中,该组件需要以下参数

  • targets: 要读取日志的文件列表。
  • forward_to: 要发送日志条目的接收器列表。
  • tail_from_end: 如果找不到存储位置,是否从文件末尾开始读取日志文件。
alloy
loki.source.file "log_scrape" {
    targets    = local.file_match.local_files.targets
    forward_to = [loki.write.local.receiver]
    tail_from_end = true
}

loki.write

loki.write 组件将日志写入 Loki 目的地。在此示例中,该组件需要以下参数

  • url: 定义将日志发送到 Loki 的完整 URL 端点。
alloy
loki.write "local" {
  endpoint {
    url = "http://loki:3100/loki/api/v1/push"
  }
}