[Help] Extracting dynamic service label from multiple folder logs in Alloy on Windows

I am using Alloy to collect logs from multiple services on a single Windows server.

The logs are organized in the following folder structure:

G:\Services\Background\\logs\<log_file>.log

Example paths:

G:\Services\Background\ServiceA\logs\default.log

G:\Services\Background\ServiceB\logs\default.log

G:\Services\Background\ServiceC\logs\default.log

I want each log sent to Loki to have a dynamic label service based on the folder name.

Currently, all logs appear in Loki with:

service_name = unknown_service

My current config.alloy:

loki.write "endpoint" {
  endpoint {
    url = "http://loki-server:3100/loki/api/v1/push"
  }
}

local.file_match "service_logs" {
  path_targets = [{
    "__path__" = "G:\\\\Services\\\\Background\\\\*\\\\logs\\\\*",
  }]
  sync_period = "60s"
}

loki.source.file "sendlogs" {
  targets    = local.file_match.service_logs.targets
  forward_to = [loki.process.parse_service_logs.receiver]
}

loki.process "parse_service_logs" {
  forward_to = [loki.write.endpoint.receiver]

  stage.multiline {
    firstline = "^\\["
  }

  stage.regex {
    source     = "filename"
    expression = "Background\\\\(?P<service>[^\\\\]+)\\\\logs.*"
  }

  stage.labels {
    values = {
      "job"      = "service_logs",
      "hostname" = sys.env("HOSTNAME"),
      "service"  = "{{ .service }}",
    }
  }
}

What I have tried:

  1. Using stage.regex with __path__ → did not work on Windows, always returns unknown_service.

  2. Using stage.regex with filename → still did not work, all logs remain unknown_service.

  3. Using stage.regex with message → works for some Windows Event logs but not for file logs.

Goal:
Extract the service name dynamically from the folder name and send it as a service label to Loki.
I want a single Alloy configuration that works for all services under G:\Services\Background\<SERVICE>\logs without installing one Alloy instance per service.

Can anyone advise on the correct way to configure Alloy on Windows to dynamically extract the service name from each folder and send it as a label to Loki?

  1. Verify your logs in Loki actually has filename label. If so then you should be good.
  2. Try changing the following line:
stage.labels {
    values = {
      "job"      = "service_logs",
      "hostname" = sys.env("HOSTNAME"),
      "service"  = "service",      # "service"  = "{{ .service }}",
    }
  }

Also, as a side note, in stage.labels all values are “references”, so the line "job" = "service_logs" also wouldn’t work, you’ll want to use static_labels for setting a static value to a label.