{"modulePath":"github.com/cloudzero/cloudzero-agent","version":"v1.3.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package logging\n\nPackage logging provides structured logging infrastructure for CloudZero Agent operations.\n\nPackage logging provides structured logging infrastructure for CloudZero Agent operations. This package implements a comprehensive logging framework built on Zerolog that enables consistent, structured logging across all CloudZero Agent components with configurable output destinations, log levels, and contextual information.\n\nThe logging infrastructure supports CloudZero Agent operational requirements including development debugging, production monitoring, audit compliance, and performance analysis through structured log events with consistent formatting and metadata.\n\nKey capabilities:\n\n  - Structured logging: JSON-formatted log events with consistent field structure\n  - Multiple sinks: Simultaneous output to multiple destinations (stdout, files, external systems)\n  - Level control: Configurable log levels for development and production environments\n  - Context integration: Automatic correlation with request contexts and tracing information\n  - Hook system: Extensible logging pipeline with custom processing hooks\n  - Attribute injection: Consistent metadata addition across all log events\n\nConfiguration patterns:\n\n  - Development: Human-readable console output with debug information\n  - Production: JSON-structured logs for aggregation and analysis\n  - Testing: Filtered output for deterministic test execution\n  - Integration: Custom sinks for external monitoring and alerting systems\n\nThe logging framework integrates with CloudZero Agent operational monitoring, providing the observability foundation for debugging, performance analysis, and compliance reporting across all agent components and deployment environments.\n\nPackage logging provides structured logging infrastructure for CloudZero Agent operations.\n\n## Functions\n\n```go\nfunc NewFieldFilterWriter(w io.Writer, fieldsToSkip []string) io.Writer\n```\nNewFieldFilterWriter creates a JSON log field filtering writer for CloudZero Agent logging. This constructor creates a writer that removes specified fields from JSON log events, enabling selective field filtering for security, privacy, and output customization.\n\nField filtering use cases:\n\n  - Security filtering: Remove authentication tokens, API keys, passwords\n  - Privacy protection: Filter user IDs, email addresses, personal information\n  - Trace cleanup: Remove tracing fields (spanId, parentSpanId) for cleaner output\n  - Environment filtering: Remove development-specific fields in production\n  - Volume reduction: Filter verbose fields to reduce log storage requirements\n\nParameters:\n\n  - w: Underlying writer for filtered output (stdout, files, external systems)\n  - fieldsToSkip: Field names to remove from JSON log events\n\nFiltering behavior:\n\n  - Only affects JSON log events; non-JSON content passes through unchanged\n  - Preserves all other fields and log structure\n  - Maintains newline formatting for consistent output\n  - Thread-safe for concurrent logging operations\n\nThe returned writer implements io.Writer and can be used anywhere standard writers are accepted in the CloudZero Agent logging pipeline.\n\n```go\nfunc NewLogger(opts ...LoggerOpt) (*zerolog.Logger, error)\n```\nNewLogger creates a configured CloudZero Agent logger with comprehensive operational capabilities. This constructor applies functional options to build a Zerolog-based logger optimized for CloudZero Agent operational requirements including structured logging, multiple outputs, and consistent metadata injection.\n\nDefault configuration:\n\n  - Log level: Info (filters out debug and trace events)\n  - Output sink: Filtered stdout with sensitive field removal\n  - Version: Automatic detection from build information\n  - Timestamp: UTC timestamps for consistent time representation\n  - Caller information: File and line number for debugging\n\nConfiguration validation:\n\n  - All options are applied and validated during construction\n  - Invalid configurations return descriptive errors\n  - Partial failures prevent logger creation\n  - Default values ensure operational logger even with minimal configuration\n\nOperational features:\n\n  - Multi-sink output: Simultaneous logging to multiple destinations\n  - Hook processing: Extensible event processing pipeline\n  - Attribute injection: Consistent metadata across all log events\n  - Context integration: Sets global context logger for request correlation\n\nError conditions:\n\n  - Invalid log level strings\n  - Failed option application\n  - Sink or hook configuration errors\n\nReturns a fully configured Zerolog logger ready for CloudZero Agent operations, or an error describing configuration failures.\n\n```go\nfunc StoreWriter(\n\tctx context.Context,\n\tstore types.WritableStore,\n\tclusterName string,\n\tcloudAccountID string,\n) io.Writer\n```\nStoreWriter creates a CloudZero metric storage writer for log event integration. This constructor creates a writer that transforms structured log events into CloudZero metrics, enabling log data to be processed through the CloudZero cost allocation and analysis pipeline.\n\nIntegration benefits:\n\n  - Unified data pipeline: Log events stored alongside other CloudZero metrics\n  - Cost attribution: Log volume attributed to specific clusters and cloud accounts\n  - Operational insights: Log patterns integrated with CloudZero analytics\n  - Storage efficiency: Leverages CloudZero metric storage and compression\n\nParameters:\n\n  - ctx: Context for storage operations and lifecycle management\n  - store: WritableStore for CloudZero metric persistence\n  - clusterName: Kubernetes cluster identification for cost attribution\n  - cloudAccountID: Cloud provider account for billing correlation\n\nThe returned writer transforms every log event into a CloudZero metric with:\n\n  - Metric name: \"log\"\n  - Value: Log message content\n  - Labels: All log event fields as key-value pairs\n  - Timestamps: Preserved from original log events\n  - Context: Cluster and cloud account attribution\n\nThis enables CloudZero platform to analyze log patterns, volume, and costs alongside other infrastructure and application metrics.\n\n## Types\n\n```go\ntype Attr func(zerolog.Context) zerolog.Context\n```\nAttr provides dynamic attribute injection for CloudZero Agent logger configuration. This function type enables flexible addition of contextual information to log events, supporting consistent metadata across different logging contexts and operational scenarios.\n\nAttribute patterns:\n\n  - Service identification: Component names, versions, and deployment information\n  - Request correlation: Request IDs, trace IDs, and user contexts\n  - Operational context: Environment, region, and cluster information\n  - Business context: Customer IDs, cost allocation metadata\n\nThe function receives a zerolog.Context and returns an enhanced context with additional fields, enabling chainable attribute addition and flexible logger customization.\n\n```go\ntype LoggerOpt = func(logger *internalLogger) error\n```\nLoggerOpt defines functional options for CloudZero Agent logger configuration. This type enables flexible, validated logger setup through composable configuration functions that modify the internal logger state during construction.\n\nThe functional options pattern provides:\n\n  - Type safety: Compile-time validation of configuration options\n  - Composability: Multiple options can be combined and reused\n  - Error handling: Each option can validate and report configuration errors\n  - Extensibility: New options can be added without breaking existing code\n\nOptions modify the internalLogger during construction and return errors for invalid configurations, enabling robust logger setup with comprehensive validation.\n\n```go\nfunc WithAttrs(attrs ...Attr) LoggerOpt\n```\nWithAttrs configures consistent attribute injection for all CloudZero Agent log events. This option enables automatic addition of contextual information to every log event, ensuring consistent metadata across all logging operations for operational visibility and correlation.\n\nAttribute injection patterns:\n\n  - Service identification: Component names, service versions, deployment information\n  - Request correlation: Request IDs, trace IDs, session identifiers\n  - Operational context: Environment, region, cluster, namespace information\n  - Business context: Customer IDs, cost allocation metadata, resource identifiers\n\nExample usage:\n\n\tlogger := NewLogger(\n\t\tWithAttrs(\n\t\t\tfunc(ctx zerolog.Context) zerolog.Context {\n\t\t\t\treturn ctx.Str(\"component\", \"webhook-controller\").\n\t\t\t\t\tStr(\"environment\", \"production\").\n\t\t\t\t\tStr(\"cluster\", \"us-west-2\")\n\t\t\t},\n\t\t),\n\t)\n\nMultiple attribute functions:\n\n  - Multiple Attr functions can be provided to this single call\n  - Functions are applied in order to build cumulative context\n  - Later functions can reference fields added by earlier functions\n  - All attributes are added to every log event automatically\n\nPerformance considerations:\n\n  - Attribute functions execute for every log event\n  - Keep attribute logic simple and efficient\n  - Consider caching expensive computations\n  - Avoid I/O operations within attribute functions\n\n```go\nfunc WithHook(hook zerolog.Hook) LoggerOpt\n```\nWithHook adds a processing hook to the CloudZero Agent logging pipeline. This option enables custom log event processing, transformation, and routing for advanced logging requirements including external system integration and custom formatting.\n\nHook capabilities:\n\n  - Event filtering: Custom logic for conditional log event processing\n  - Field transformation: Modify or enhance log event fields\n  - External routing: Send specific events to external systems\n  - Compliance processing: Add regulatory or audit-specific information\n  - Performance monitoring: Track logging performance and patterns\n\nCommon hook use cases:\n\n  - Security filtering: Remove sensitive information from log events\n  - Alerting integration: Forward critical events to alerting systems\n  - Audit compliance: Add regulatory metadata for compliance requirements\n  - Performance tracking: Measure and report logging performance metrics\n  - Custom formatting: Apply organization-specific log formatting\n\nMultiple hooks support:\n\n  - This function can be called multiple times to add multiple hooks\n  - Hooks are executed in the order they are added\n  - Hook failures do not prevent log event processing\n  - Each hook receives the log event independently\n\nHooks execute synchronously and should be designed for minimal performance impact.\n\n```go\nfunc WithLevel(level string) LoggerOpt\n```\nWithLevel configures the minimum log level for CloudZero Agent logger output filtering. This option enables appropriate verbosity control across different deployment environments, optimizing performance and ensuring suitable log output for development and production.\n\nSupported log levels (from most to least verbose):\n\n  - \"trace\": Detailed execution flow for deep debugging\n  - \"debug\": Development debugging information\n  - \"info\": General operational information (default)\n  - \"warn\": Warning conditions that should be noted\n  - \"error\": Error conditions requiring attention\n  - \"fatal\": Critical errors causing application termination\n  - \"panic\": Panic conditions with stack traces\n\nLevel selection guidelines:\n\n  - Development: \"debug\" or \"trace\" for comprehensive debugging\n  - Testing: \"warn\" or \"error\" to reduce noise\n  - Production: \"info\" for operational visibility\n  - Troubleshooting: Temporarily lower levels for issue diagnosis\n\nReturns an error if the level string is not recognized or valid.\n\n```go\nfunc WithSink(sink io.Writer) LoggerOpt\n```\nWithSink adds an output destination for CloudZero Agent log events. This option enables simultaneous log output to multiple destinations including console output, files, and external logging systems for comprehensive observability.\n\nCommon sink configurations:\n\n  - os.Stdout: Console output for development and container logging\n  - File writers: Persistent log files for audit and analysis\n  - Network writers: Integration with external logging systems\n  - Filtered writers: Custom filtering and formatting for specific requirements\n\nMultiple sinks support:\n\n  - This function can be called multiple times to add multiple output destinations\n  - All sinks receive identical log events simultaneously\n  - Each sink can apply independent filtering and formatting\n  - Failed sinks do not affect other sink operations\n\nOperational benefits:\n\n  - Console output for real-time monitoring during development\n  - File output for persistent storage and analysis\n  - External system integration for centralized logging and alerting\n  - Backup logging destinations for reliability\n\nThe sink receives all log events that pass the configured log level threshold.\n\n```go\nfunc WithVersion(version string) LoggerOpt\n```\nWithVersion specifies custom version information for CloudZero Agent log events. This option overrides the default version from the build library, enabling custom version identification for special deployments, development builds, or testing scenarios.\n\nVersion information usage:\n\n  - Log correlation: Track issues across different agent versions\n  - Debugging support: Identify version-specific behaviors and bugs\n  - Operational monitoring: Monitor version distribution across deployments\n  - Compliance tracking: Maintain version audit trails for regulatory requirements\n\nDefault behavior:\n\n  - If not specified, version is automatically retrieved from build.GetVersion()\n  - Build version includes Git commit, build time, and release information\n  - Production deployments typically use automatic version detection\n\nCustom version scenarios:\n\n  - Development builds: Custom identifiers for local development\n  - Testing environments: Test-specific version markers\n  - Special deployments: Custom deployment identifiers\n  - Integration testing: Version markers for test correlation\n\nThe version appears in all log events as a consistent field for operational visibility.\n\n","path":"github.com/cloudzero/cloudzero-agent/app/logging","name":"logging","synopsis":"Package logging provides structured logging infrastructure for CloudZero Agent operations.","isRedistributable":true}
