kube-state-logs
AGENTS.md4 starsChanged 3 months agoMITView on GitHub
This document provides guidance for AI agents working with the kube-state-logs codebase. kube-state-logs is a Kubernetes cluster state logger that outputs structured JSON logs. It's inspired by kube-state-metrics but produces logs instead of Prometheus metrics. Each Kubernetes resource type has a dedicated handler in pkg/collector/resources/. Follow this pattern: All resource handlers must implement the interfaces.ResourceHandler interface: GetInformers must include dependency caches as well as the primary cache so the collector can handle built-in informer failures consistently. Handlers embedding utils.BaseHandler inherit…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
25 rules. About 0 are common, 6 are distinctive, and 19 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
19
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 55
Use JSON tags with PascalCase field names (e.g., json:"FieldName")
- Distinctive: line 59
Test informer setup and data collection logic
- Very specific: line 63
All resource handlers must implement the interfaces.ResourceHandler interface:
- Very specific: line 117
Use table-driven tests with []struct{ name string.
- Distinctive: line 134
When updating the Go version, the following files must be changed:
- Very specific: line 136
go.mod: - Update the go directive (e.g., go 1.27.1) - Very specific: line 137
Dockerfile: - Update GO_VERSION and the GO_SHA256SUM_* values - Very specific: line 138
.github/workflows/ci.yml: - Update go-version in setup-go jobs - Distinctive: line 139
AGENTS.md: - Update the documented Go version in Project Overview - Very specific: line 168
After updating, run tests to ensure compatibility: go test ./...
- Distinctive: line 169
Check the Kubernetes client-go compatibility matrix for supported Kubernetes versions
- Very specific: line 212
Create handler in pkg/collector/resources/newresource.go
- Very specific: line 221
Add tests in pkg/collector/resources/newresource_test.go
- Very specific: line 222
Update Helm chart RBAC in charts/kube-state-logs/templates/rbac.yaml if new permissions needed (update both simple and advanced mode …
- Very specific: line 224
Document the new resource in docs/resources.md under the appropriate category
- Very specific: line 225
If the resource should be enabled by default, add it to config.resources in charts/kube-state-logs/values.yaml and update docs accordingly.
- Distinctive: line 234
When modifying Helm templates:
- Very specific: line 242
Update the relevant struct in pkg/types/types.go
- Very specific: line 248
Add field to Config struct in pkg/config/config.go
- Very specific: line 249
Add parsing logic in config.go
- Very specific: line 250
Update Helm chart values.yaml and templates
- Very specific: line 255
Code Style: Write idiomatic Go code and ensure all code is properly formatted with gofmt
- Distinctive: line 256
JSON Field Names: Use PascalCase in JSON tags to match existing output format
- Very specific: line 257
Informers: Always use informer cache via SafeGetStoreList(), not direct API calls
- Very specific: line 258
Namespace Filtering: Use utils.ShouldIncludeNamespace() for consistent behavior
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md - AI Agent Guidelines
This document provides guidance for AI agents working with the kube-state-logs codebase.
Project Overview
kube-state-logs is a Kubernetes cluster state logger that outputs structured JSON logs. It's inspired by kube-state-metrics but produces logs instead of Prometheus metrics.
- Language: Go 1.27.1+
- Primary Dependencies: k8s.io/client-go, k8s.io/api, k8s.io/apimachinery
- Deployment: Helm chart in
charts/kube-state-logs/
Project Structure
├── main.go # Application entrypoint
├── pkg/
│ ├── collector/
│ │ ├── collector.go # Main collector orchestration
│ │ ├── logger.go # Logging utilities
│ │ └── resources/ # Resource handlers (one per K8s resource type)
│ │ ├── deployment.go
│ │ ├── pod.go
│ │ ├── node.go
│ │ └── ...
│ ├── config/
│ │ └── config.go # Configuration parsing and validation
│ ├── interfaces/
│ │ └── logger.go # Interface definitions
│ ├── types/
│ │ └── types.go # Data structures for log entries
│ └── utils/ # Shared utilities
│ ├── handler_boilerplate.go
│ ├── informer_utils.go
│ ├── k8s_field_extraction.go
│ └── ...
├── charts/kube-state-logs/ # Helm chart for deployment
└── docs/ # Additional documentationCode Patterns & Conventions
Adding a New Resource Handler
Each Kubernetes resource type has a dedicated handler in pkg/collector/resources/. Follow this pattern:
- Create the handler file (e.g.,
myresource.go):- Define a
MyResourceHandlerstruct embeddingutils.BaseHandler - Implement
NewMyResourceHandler(client kubernetes.Interface)constructor - Implement
SetupInformer()to configure the Kubernetes informer - Implement
Collect()to gather and format resource data
- Define a
- Create the data type in
pkg/types/types.go:- Define
MyResourceDatastruct with appropriate metadata embedding - Use JSON tags with PascalCase field names (e.g.,
json:"FieldName")
- Define
- Create tests in
myresource_test.go:- Use table-driven tests
- Test informer setup and data collection logic
Handler Interface
All resource handlers must implement the interfaces.ResourceHandler interface:
type ResourceHandler interface {
SetupInformer(factory informers.SharedInformerFactory, logger Logger, resyncPeriod time.Duration) error
GetInformers() []cache.SharedIndexInformer
Collect(ctx context.Context, namespaces []string) ([]any, error)
}GetInformers must include dependency caches as well as the primary cache so
the collector can handle built-in informer failures consistently. Handlers
embedding utils.BaseHandler inherit the primary-cache implementation;
override it to include any dependency informers.
Data Types Pattern
Log entry types follow a composition pattern using embedded structs:
BaseMetadata- Core fields (Timestamp, ResourceType, Name, CreatedTimestamp)NamespacedMetadata- Adds Namespace fieldLabeledMetadata- Adds Labels and Annotations mapsNamespacedLabeledMetadata- Combines namespaced + labeledControllerCreatedResourceMetadata- Adds CreatedByKind/CreatedByName
Utility Functions
Common utilities in pkg/utils/:
utils.NewBaseHandler()- Base handler constructorutils.SafeGetStoreList()- Safe informer cache accessutils.ShouldIncludeNamespace()- Namespace filteringutils.ConvertConditionStatus()- Convert K8s condition status to boolean pointer
Testing
Running Tests
# Run all tests
go test ./...
# Run tests with verbose output
go test -v ./...
# Run specific package tests
go test -v ./pkg/collector/resources/...
# Run specific test
go test -v -run TestDeploymentHandler ./pkg/collector/resources/Test Patterns
- Use table-driven tests with
[]struct{ name string; ... }slices - Mock Kubernetes clients using fake clientsets from
k8s.io/client-go/kubernetes/fake - Always run
go test ./...andgofmt -l .before submitting changes - CI will fail if tests don't pass or code isn't formatted
Building & Development
Docker Image & FIPS Compliance
The Dockerfile uses Azure Linux with Microsoft Go for FIPS (Federal Information Processing Standards) compliance:
- Source stage:
mcr.microsoft.com/azurelinux/base/core:3.0 - Go version:
ARG GO_VERSION=1.27.1 - Runtime stage:
mcr.microsoft.com/azurelinux/distroless/minimal:3.0 - Crypto backend: Microsoft Go 1.27 enables the OpenSSL backend by default; no
GOEXPERIMENToverride is needed.
Updating Go Version
When updating the Go version, the following files must be changed:
go.mod- Update thegodirective (e.g.,go 1.27.1)Dockerfile- UpdateGO_VERSIONand theGO_SHA256SUM_*values.github/workflows/ci.yml- Updatego-versionin setup-go jobsAGENTS.md- Update the documented Go version in Project Overview
Example version update:
# go.mod
go 1.27.1
# Dockerfile
ARG GO_VERSION=1.27.1
# .github/workflows/ci.yml
go-version: '1.27.1'Updating Kubernetes API Version
The Kubernetes client libraries must be updated together as they share version numbers. Use go get commands rather than editing go.mod directly:
# Update all k8s.io dependencies to a new version (e.g., v0.34.0)
go get k8s.io/api@v0.34.0 k8s.io/apimachinery@v0.34.0 k8s.io/client-go@v0.34.0 k8s.io/metrics@v0.34.0
# Clean up and update go.sum
go mod tidyImportant notes:
- All
k8s.io/api,k8s.io/apimachinery,k8s.io/client-go, andk8s.io/metricsshould use the same version k8s.io/klog/v2andk8s.io/utilsare versioned independently and usually don't need updating- After updating, run tests to ensure compatibility:
go test ./... - Check the Kubernetes client-go compatibility matrix for supported Kubernetes versions
Local Build
# Build Docker image
make build
# Build for multiple platforms
make build-multi
# Push to registry
make pushEnvironment Variables
IMAGE_NAME- Docker image name (default:kube-state-logs)IMAGE_TAG- Docker image tag (default:latest)REGISTRY- Container registry (default:ghcr.io/azure/)
Configuration
Key configuration options (set via Helm values or environment):
deploymentMode- Deployment architecture:simple(single Deployment) oradvanced(DaemonSet + Deployment)logInterval- How often to log resource state (default:1m)logLevel- Log verbosity: debug, info, warn, errornamespaces- Comma-separated namespaces to monitor (empty = all)resources- Which resource types to monitor
Command-Line Flags for Node Filtering
--node=<name>- Filter pods to only those scheduled on this node (used by DaemonSet in advanced mode)--track-unscheduled-pods- Only collect pods not yet scheduled to a node (used by Deployment in advanced mode)--use-kubelet-api- Poll local kubelet/podsand/stats/summaryfor pod/container snapshots--node-ip=<address>- Node address used for direct kubelet access--kubelet-insecure-skip-verify- Explicitly disable kubelet serving-certificate verification
Common Tasks
Adding Support for a New Kubernetes Resource
- Create handler in
pkg/collector/resources/newresource.go - Define data type in
pkg/types/types.go - Register handler in
pkg/collector/collector.goby adding to thehandlersmap inregisterHandlers():handlers := map[string]interfaces.ResourceHandler{ // ... existing handlers ... "newresource": resources.NewNewResourceHandler(c.client), } - Add tests in
pkg/collector/resources/newresource_test.go - Update Helm chart RBAC in
charts/kube-state-logs/templates/rbac.yamlif new permissions needed (update both simple and advanced mode sections) - For CamelCase resources (e.g.,
PodDisruptionBudget,NetworkPolicy): Add a mapping in theresourceSnapshotNamehelper incharts/kube-state-logs/templates/_helpers.tplto convert the lowercase resource name to the proper PascalCase snapshot name (e.g.,poddisruptionbudget→PodDisruptionBudgetSnapshot) - Document the new resource in
docs/resources.mdunder the appropriate category - If the resource should be enabled by default, add it to
config.resourcesincharts/kube-state-logs/values.yamland update docs accordingly.
Working with Deployment Modes
The Helm chart supports two deployment modes controlled by deploymentMode:
- simple: Single Deployment with all resources (default)
- advanced: DaemonSet for pod/container + Deployment for other resources
When modifying Helm templates:
templates/deployment.yaml- Handles both simple mode (full deployment) and advanced mode (cluster deployment)templates/daemonset.yaml- Only rendered in advanced mode, handles pod/container with node filteringtemplates/rbac.yaml- Contains conditional RBAC for both modes (simple uses single set, advanced uses separate -node and -cluster RBAC)templates/_helpers.tpl- Contains helpers for resource filtering (clusterResources) and ADX-Mon annotations (nodeLogKeysAnnotation,clusterLogKeysAnnotation)
Modifying Log Output Format
- Update the relevant struct in
pkg/types/types.go - Modify
createLogEntry()in the resource handler - Update corresponding tests
Adding New Configuration Options
- Add field to
Configstruct inpkg/config/config.go - Add parsing logic in config.go
- Update Helm chart
values.yamland templates - Update documentation
Important Notes
- Code Style: Write idiomatic Go code and ensure all code is properly formatted with
gofmt - JSON Field Names: Use PascalCase in JSON tags to match existing output format
- Informers: Always use informer cache via
SafeGetStoreList(), not direct API calls - Namespace Filtering: Use
utils.ShouldIncludeNamespace()for consistent behavior - Error Handling: Log errors with context using
klogpackage - Nil Checks: Kubernetes API objects often have nil pointers; always check before dereferencing
CI/CD Pipeline
The project uses GitHub Actions (.github/workflows/ci.yml) for continuous integration:
- On Pull Requests: Runs
gofmtcheck, unit tests, and Helm lint - On Push to
main: Builds and publishes Docker images and Helm charts to GHCR - On Version Tags (
v*): Creates versioned releases with proper semver tags
See docs/releasing.md for full versioning strategy and release process.
Related Documentation
- README.md - Project overview and installation
- docs/adx-mon-integration.md - ADX-Mon log collection setup
- docs/releasing.md - Release process
- SUPPORT.md - Support information
- SECURITY.md - Security policy
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

