Skip to content

Commit

Permalink
Add ContainerJSON to label template data
Browse files Browse the repository at this point in the history
  • Loading branch information
jan4843 committed Dec 21, 2023
1 parent 8e5ebd9 commit ee07ed9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ services:
build: https://github.com/jan4843/docker_stats_exporter.git
environment:
LABEL_state: '{{.Container.State}}'
LABEL_health: '{{.ContainerJSON.State.Health.Status}}'
LABEL_compose_project: '{{index .Container.Labels "com.docker.compose.project"}}'
ports:
- 9338:9338
Expand All @@ -38,9 +39,9 @@ By default, metrics are retrieved from the Docker socket at `/var/run/docker.soc

The only label exposed for all metrics is `name`, the container name.

To expose additional labels, environmental variables with a `LABEL_` prefix are used. The environmental variable name (excluding the prefix) is used as the metric name, and its value [Go-templated](https://pkg.go.dev/text/template) on a [`Container` struct](https://pkg.go.dev/github.com/docker/docker/api/types#Container).
To expose additional labels, environmental variables with a `LABEL_` prefix are used. The environmental variable name (excluding the prefix) is used as the metric name, and its value [Go-templated](https://pkg.go.dev/text/template) with [`Container` struct](https://pkg.go.dev/github.com/docker/docker/api/types#Container) and [`ContainerJSON` struct](https://pkg.go.dev/github.com/docker/docker/api/types#ContainerJSON) variables in scope.

See the Docker Compose example above adding the `state` and `compose_project` metric labels.
See the Docker Compose example above adding the `state`, `health`, and `compose_project` metric labels.

## Metrics

Expand Down
13 changes: 12 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,21 @@ func (e *exporter) Collect(ch chan<- prometheus.Metric) {
}

func (e *exporter) collectContainer(container *types.Container, ch chan<- prometheus.Metric) error {
containerJson, err := e.docker.ContainerInspect(context.TODO(), container.ID)
if err != nil {
return err
}

labelsNames := []string{"name"}
labelsValues := []string{strings.Trim(container.Names[0], "/")}
for labelName, labelTemplate := range e.extraLabels {
templateData := struct{ Container *types.Container }{container}
templateData := struct {
Container *types.Container
ContainerJSON types.ContainerJSON
}{
container,
containerJson,
}
var labelValue bytes.Buffer
labelTemplate.Execute(&labelValue, templateData)
labelsNames = append(labelsNames, labelName)
Expand Down

0 comments on commit ee07ed9

Please sign in to comment.