logging

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: Apache-2.0, BSD-3-Clause, MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AvailableFormatVariables = []FormatVariable{
	{"$remote_addr", "Client IP address", "192.168.1.1"},
	{"$remote_user", "Client user name (from auth)", "-"},
	{"$time_local", "Local time in Common Log Format", "02/Jan/2006:15:04:05 -0700"},
	{"$time_iso8601", "ISO 8601 time format", "2006-01-02T15:04:05-07:00"},
	{"$time_unix", "Unix timestamp in seconds", "1704067200"},
	{"$time_msec", "Unix timestamp with milliseconds", "1704067200.123"},
	{"$request", "Full request line", "GET /search?q=test HTTP/1.1"},
	{"$request_method", "HTTP method", "GET"},
	{"$request_uri", "Full request URI with query string", "/search?q=test"},
	{"$request_path", "Request path only (no query string)", "/search"},
	{"$query_string", "Query string without ?", "q=test"},
	{"$status", "HTTP response status code", "200"},
	{"$body_bytes_sent", "Response body size in bytes", "1234"},
	{"$bytes_sent", "Total bytes sent (headers + body)", "1456"},
	{"$http_referer", "Referer header", "https://example.com/"},
	{"$http_user_agent", "User-Agent header", "Mozilla/5.0 ..."},
	{"$http_host", "Host header", "example.com"},
	{"$http_x_forwarded_for", "X-Forwarded-For header", "10.0.0.1"},
	{"$http_x_real_ip", "X-Real-IP header", "10.0.0.1"},
	{"$server_protocol", "Request protocol", "HTTP/1.1"},
	{"$request_time", "Request processing time in seconds with ms precision", "0.123"},
	{"$request_time_ms", "Request processing time in milliseconds", "123"},
	{"$request_id", "Unique request ID (if set)", "550e8400-e29b-41d4-a716-446655440000"},
	{"$connection", "Connection serial number", "12345"},
	{"$connection_requests", "Number of requests on this connection", "3"},
	{"$ssl_protocol", "SSL protocol (TLSv1.2, TLSv1.3, etc.)", "TLSv1.3"},
	{"$ssl_cipher", "SSL cipher used", "TLS_AES_128_GCM_SHA256"},
	{"$hostname", "Server hostname", "search.example.com"},
	{"$pid", "Process ID", "12345"},
}

AvailableFormatVariables lists all supported format variables

Functions

func ValidateFormat

func ValidateFormat(format string) []string

ValidateFormat validates a custom format string and returns any unknown variables

Types

type AccessEntry

type AccessEntry struct {
	Timestamp          time.Time `json:"timestamp"`
	IP                 string    `json:"ip"`
	Method             string    `json:"method"`
	Path               string    `json:"path"`
	QueryString        string    `json:"query_string,omitempty"`
	Protocol           string    `json:"protocol"`
	Status             int       `json:"status"`
	Size               int64     `json:"size"`
	BytesSent          int64     `json:"bytes_sent"`
	Referer            string    `json:"referer"`
	UserAgent          string    `json:"user_agent"`
	Latency            int64     `json:"latency_ms"`
	RequestID          string    `json:"request_id,omitempty"`
	RemoteUser         string    `json:"remote_user,omitempty"`
	Host               string    `json:"host,omitempty"`
	XForwardedFor      string    `json:"x_forwarded_for,omitempty"`
	XRealIP            string    `json:"x_real_ip,omitempty"`
	SSLProtocol        string    `json:"ssl_protocol,omitempty"`
	SSLCipher          string    `json:"ssl_cipher,omitempty"`
	Connection         int64     `json:"connection,omitempty"`
	ConnectionRequests int       `json:"connection_requests,omitempty"`
}

AccessEntry represents an access log entry with all fields for custom formatting

type AccessLogger

type AccessLogger struct {
	// contains filtered or unexported fields
}

AccessLogger logs HTTP access in Combined Log Format

func NewAccessLogger

func NewAccessLogger(path string) *AccessLogger

NewAccessLogger creates a new access logger

func (*AccessLogger) Close

func (l *AccessLogger) Close() error

Close closes the access logger

func (*AccessLogger) GetCustomFormat

func (l *AccessLogger) GetCustomFormat() string

GetCustomFormat returns the current custom format string

func (*AccessLogger) Log

func (l *AccessLogger) Log(entry AccessEntry)

Log logs an access entry

func (*AccessLogger) LogRequest

func (l *AccessLogger) LogRequest(r *http.Request, status int, size int64, latency time.Duration)

LogRequest logs an HTTP request

func (*AccessLogger) LogRequestWithID

func (l *AccessLogger) LogRequestWithID(r *http.Request, status int, size int64, latency time.Duration, requestID string)

LogRequestWithID logs an HTTP request with a request ID

func (*AccessLogger) Rotate

func (l *AccessLogger) Rotate() error

Rotate rotates the access log file

func (*AccessLogger) SetCustomFormat

func (l *AccessLogger) SetCustomFormat(format string)

SetCustomFormat sets a custom log format with variables Example: "$remote_addr - $remote_user [$time_local] \"$request\" $status $body_bytes_sent"

func (*AccessLogger) SetFormat

func (l *AccessLogger) SetFormat(format string)

SetFormat sets the log format

type AuditAction

type AuditAction string

AuditAction represents an audit event type per AI.md PART 11 lines 11772-11936 Uses dot notation: category.action (e.g., admin.login, user.created)

const (
	// Admin events (PART 11 lines 11772-11786)
	AuditActionLogin            AuditAction = "admin.login"
	AuditActionLogout           AuditAction = "admin.logout"
	AuditActionLoginFailed      AuditAction = "admin.login_failed"
	AuditActionAdminCreated     AuditAction = "admin.created"
	AuditActionAdminDeleted     AuditAction = "admin.deleted"
	AuditActionPasswordChanged  AuditAction = "admin.password_changed"
	AuditActionMFAEnabled       AuditAction = "admin.mfa_enabled"
	AuditActionMFADisabled      AuditAction = "admin.mfa_disabled"
	AuditActionTokenRegenerated AuditAction = "admin.token_regenerated"
	AuditActionSessionExpired   AuditAction = "admin.session_expired"
	AuditActionSessionRevoked   AuditAction = "admin.session_revoked"

	// User events (PART 11 lines 11788-11807)
	AuditActionUserRegistered        AuditAction = "user.registered"
	AuditActionUserLogin             AuditAction = "user.login"
	AuditActionUserLogout            AuditAction = "user.logout"
	AuditActionUserLoginFailed       AuditAction = "user.login_failed"
	AuditActionUserCreate            AuditAction = "user.created"
	AuditActionUserDelete            AuditAction = "user.deleted"
	AuditActionUserSuspended         AuditAction = "user.suspended"
	AuditActionUserUnsuspended       AuditAction = "user.unsuspended"
	AuditActionUserRoleChanged       AuditAction = "user.role_changed"
	AuditActionUserPasswordChanged   AuditAction = "user.password_changed"
	AuditActionUserPasswordResetReq  AuditAction = "user.password_reset_requested"
	AuditActionUserPasswordResetDone AuditAction = "user.password_reset_completed"
	AuditActionUserEmailVerified     AuditAction = "user.email_verified"
	AuditActionUserMFAEnabled        AuditAction = "user.mfa_enabled"
	AuditActionUserMFADisabled       AuditAction = "user.mfa_disabled"
	AuditActionUserRecoveryKeyUsed   AuditAction = "user.recovery_key_used"

	// Organization events (PART 11 lines 11809-11827)
	AuditActionOrgCreated           AuditAction = "org.created"
	AuditActionOrgDeleted           AuditAction = "org.deleted"
	AuditActionOrgSettingsUpdated   AuditAction = "org.settings_updated"
	AuditActionOrgMemberInvited     AuditAction = "org.member_invited"
	AuditActionOrgMemberJoined      AuditAction = "org.member_joined"
	AuditActionOrgMemberRemoved     AuditAction = "org.member_removed"
	AuditActionOrgMemberLeft        AuditAction = "org.member_left"
	AuditActionOrgRoleChanged       AuditAction = "org.role_changed"
	AuditActionOrgRoleCreated       AuditAction = "org.role_created"
	AuditActionOrgRoleUpdated       AuditAction = "org.role_updated"
	AuditActionOrgRoleDeleted       AuditAction = "org.role_deleted"
	AuditActionOrgTokenCreated      AuditAction = "org.token_created"
	AuditActionOrgTokenRevoked      AuditAction = "org.token_revoked"
	AuditActionOrgOwnershipTransfer AuditAction = "org.ownership_transferred"
	AuditActionOrgBillingUpdated    AuditAction = "org.billing_updated"

	// Configuration events (PART 11 lines 11884-11897)
	AuditActionConfigChange         AuditAction = "config.updated"
	AuditActionConfigSMTPUpdated    AuditAction = "config.smtp_updated"
	AuditActionConfigSSLUpdated     AuditAction = "config.ssl_updated"
	AuditActionConfigSSLExpired     AuditAction = "config.ssl_expired"
	AuditActionConfigTorRegen       AuditAction = "config.tor_address_regenerated"
	AuditActionConfigBrandingUpdate AuditAction = "config.branding_updated"
	AuditActionConfigOIDCAdded      AuditAction = "config.oidc_provider_added"
	AuditActionConfigOIDCRemoved    AuditAction = "config.oidc_provider_removed"
	AuditActionConfigLDAPUpdated    AuditAction = "config.ldap_updated"
	AuditActionConfigAdminGroups    AuditAction = "config.admin_groups_updated"

	// Security events (PART 11 lines 11899-11910)
	AuditActionRateLimitExceeded  AuditAction = "security.rate_limit_exceeded"
	AuditActionIPBlocked          AuditAction = "security.ip_blocked"
	AuditActionIPUnblocked        AuditAction = "security.ip_unblocked"
	AuditActionCountryBlocked     AuditAction = "security.country_blocked"
	AuditActionCSRFFailure        AuditAction = "security.csrf_failure"
	AuditActionInvalidToken       AuditAction = "security.invalid_token"
	AuditActionBruteForceDetected AuditAction = "security.brute_force_detected"
	AuditActionSuspiciousActivity AuditAction = "security.suspicious_activity"

	// Token events (PART 11 lines 11912-11919)
	AuditActionTokenCreate  AuditAction = "token.created"
	AuditActionTokenRevoke  AuditAction = "token.revoked"
	AuditActionTokenExpired AuditAction = "token.expired"
	AuditActionTokenUsed    AuditAction = "token.used"

	// Backup & System events (PART 11 lines 11921-11935)
	AuditActionBackupCreate       AuditAction = "backup.created"
	AuditActionBackupRestore      AuditAction = "backup.restored"
	AuditActionBackupDelete       AuditAction = "backup.deleted"
	AuditActionBackupFailed       AuditAction = "backup.failed"
	AuditActionServerStarted      AuditAction = "server.started"
	AuditActionServerStopped      AuditAction = "server.stopped"
	AuditActionMaintenanceEntered AuditAction = "server.maintenance_entered"
	AuditActionMaintenanceExited  AuditAction = "server.maintenance_exited"
	AuditActionServerUpdated      AuditAction = "server.updated"
	AuditActionSchedulerTaskFail  AuditAction = "scheduler.task_failed"
	AuditActionSchedulerTaskRun   AuditAction = "scheduler.task_manual_run"

	// Cluster events (PART 11 lines 11937-11945)
	AuditActionClusterNodeJoined  AuditAction = "cluster.node_joined"
	AuditActionClusterNodeRemoved AuditAction = "cluster.node_removed"
	AuditActionClusterNodeFailed  AuditAction = "cluster.node_failed"
	AuditActionClusterTokenGen    AuditAction = "cluster.token_generated"
	AuditActionClusterModeChanged AuditAction = "cluster.mode_changed"

	// Legacy aliases for backward compatibility
	AuditActionReload           AuditAction = "config.reload"
	AuditActionEngineToggle     AuditAction = "config.engine_toggle"
	AuditActionAdminInvite      AuditAction = "admin.invite"
	AuditActionPermissionChange AuditAction = "user.permission_change"
)

type AuditActor

type AuditActor struct {
	Type      string `json:"type,omitempty"`       // Actor type: admin, user, system
	ID        string `json:"id,omitempty"`         // Actor's user ID
	Username  string `json:"username,omitempty"`   // Actor's username (for display)
	IP        string `json:"ip"`                   // IP address
	UserAgent string `json:"user_agent,omitempty"` // User agent string
}

AuditActor represents who performed the action per AI.md PART 11

type AuditCategory

type AuditCategory string

AuditCategory represents audit event categories per AI.md PART 11

const (
	AuditCategoryAuth         AuditCategory = "authentication" // Authentication events
	AuditCategoryAdmin        AuditCategory = "admin"          // Admin panel actions
	AuditCategoryConfig       AuditCategory = "configuration"  // Configuration changes
	AuditCategoryUser         AuditCategory = "users"          // User management
	AuditCategorySecurity     AuditCategory = "security"       // Security-related events
	AuditCategoryData         AuditCategory = "backup"         // Backup/data operations
	AuditCategorySystem       AuditCategory = "server"         // Server/system operations
	AuditCategoryTokens       AuditCategory = "tokens"         // Token events
	AuditCategoryCluster      AuditCategory = "cluster"        // Cluster events
	AuditCategoryOrganization AuditCategory = "organization"   // Organization events
)

type AuditEntry

type AuditEntry struct {
	ID       string                 `json:"id"`                // ULID format: audit_01HQXYZ...
	Time     time.Time              `json:"time"`              // ISO 8601 timestamp with milliseconds, UTC
	Event    AuditAction            `json:"event"`             // Event type (e.g., admin.login)
	Category AuditCategory          `json:"category"`          // Event category
	Severity AuditSeverity          `json:"severity"`          // info, warn, error, critical
	Actor    AuditActor             `json:"actor"`             // Who performed the action
	Target   *AuditTarget           `json:"target,omitempty"`  // What was acted upon
	Details  map[string]interface{} `json:"details,omitempty"` // Event-specific details
	Result   string                 `json:"result"`            // "success" or "failure"
	NodeID   string                 `json:"node_id,omitempty"` // Node ID (cluster mode)
	Reason   string                 `json:"reason,omitempty"`  // Reason for action (if provided)
}

AuditEntry represents an audit log entry per AI.md PART 11 lines 11947-11997 Uses ULID format IDs: audit_01HQXYZ123ABC

type AuditExportFormat

type AuditExportFormat string

AuditExportFormat defines the export format

const (
	AuditExportJSON AuditExportFormat = "json"
	AuditExportCSV  AuditExportFormat = "csv"
)

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

AuditLogger logs administrative actions

func NewAuditLogger

func NewAuditLogger(path string) *AuditLogger

NewAuditLogger creates a new audit logger

func (*AuditLogger) CleanupAuditLogs

func (l *AuditLogger) CleanupAuditLogs(policy AuditRetentionPolicy) (int, error)

CleanupAuditLogs removes old audit entries based on retention policy Returns the number of entries removed

func (*AuditLogger) Close

func (l *AuditLogger) Close() error

Close closes the audit logger

func (*AuditLogger) ExportAuditLogs

func (l *AuditLogger) ExportAuditLogs(opts AuditQueryOptions, format AuditExportFormat, w io.Writer) error

ExportAuditLogs exports audit logs to the specified format

func (*AuditLogger) GetAuditStats

func (l *AuditLogger) GetAuditStats() (*AuditStats, error)

GetAuditStats returns statistics about the audit log

func (*AuditLogger) Log

func (l *AuditLogger) Log(entry AuditEntry)

Log logs an audit event per AI.md PART 11

func (*AuditLogger) Log2FADisable

func (l *AuditLogger) Log2FADisable(actor, ip, targetUser string)

Log2FADisable logs 2FA disablement per AI.md PART 11 line 11806

func (*AuditLogger) Log2FAEnable

func (l *AuditLogger) Log2FAEnable(user, ip string)

Log2FAEnable logs 2FA enablement per AI.md PART 11 line 11805

func (*AuditLogger) LogAdminCreated

func (l *AuditLogger) LogAdminCreated(actor, ip, newAdmin string)

LogAdminCreated logs admin account creation

func (*AuditLogger) LogAdminDeleted

func (l *AuditLogger) LogAdminDeleted(actor, ip, deletedAdmin string)

LogAdminDeleted logs admin account deletion

func (*AuditLogger) LogBackupCreate

func (l *AuditLogger) LogBackupCreate(user, ip, filename string)

LogBackupCreate logs a backup creation per AI.md PART 11 line 11925

func (*AuditLogger) LogBackupDelete

func (l *AuditLogger) LogBackupDelete(actor, ip, filename string)

LogBackupDelete logs backup deletion

func (*AuditLogger) LogBackupFailed

func (l *AuditLogger) LogBackupFailed(actor, ip, reason string)

LogBackupFailed logs backup failure

func (*AuditLogger) LogBackupRestore

func (l *AuditLogger) LogBackupRestore(user, ip, filename string, success bool)

LogBackupRestore logs a backup restoration per AI.md PART 11 line 11926

func (*AuditLogger) LogBruteForceDetected

func (l *AuditLogger) LogBruteForceDetected(ip, path string, attempts int)

LogBruteForceDetected logs brute force detection

func (*AuditLogger) LogCSRFFailure

func (l *AuditLogger) LogCSRFFailure(ip, path string)

LogCSRFFailure logs CSRF token failure

func (*AuditLogger) LogClusterNodeFailed

func (l *AuditLogger) LogClusterNodeFailed(nodeID, reason string)

LogClusterNodeFailed logs node failure in cluster

func (*AuditLogger) LogClusterNodeJoined

func (l *AuditLogger) LogClusterNodeJoined(nodeID, nodeAddress string)

LogClusterNodeJoined logs node joining cluster

func (*AuditLogger) LogClusterNodeRemoved

func (l *AuditLogger) LogClusterNodeRemoved(actor, ip, nodeID, reason string)

LogClusterNodeRemoved logs node removal from cluster

func (*AuditLogger) LogConfigChange

func (l *AuditLogger) LogConfigChange(user, ip, resource, details string)

LogConfigChange logs a configuration change per AI.md PART 11 line 11888

func (*AuditLogger) LogConfigUpdated

func (l *AuditLogger) LogConfigUpdated(actor, ip, configSection, field string, oldValue, newValue interface{})

LogConfigUpdated logs configuration update with specific field

func (*AuditLogger) LogEngineToggle

func (l *AuditLogger) LogEngineToggle(user, ip, engine string, enabled bool)

LogEngineToggle logs an engine enable/disable

func (*AuditLogger) LogEvent

func (l *AuditLogger) LogEvent(event AuditAction, category AuditCategory, severity AuditSeverity, actor AuditActor, target *AuditTarget, result string, details map[string]interface{}, reason string)

LogEvent logs a generic audit event with full control over all fields

func (*AuditLogger) LogIPBlocked

func (l *AuditLogger) LogIPBlocked(actor, ip, blockedIP, reason string)

LogIPBlocked logs IP blocking

func (*AuditLogger) LogIPUnblocked

func (l *AuditLogger) LogIPUnblocked(actor, ip, unblockedIP string)

LogIPUnblocked logs IP unblocking

func (*AuditLogger) LogInvalidToken

func (l *AuditLogger) LogInvalidToken(ip, path, tokenType string)

LogInvalidToken logs invalid token usage

func (*AuditLogger) LogLogin

func (l *AuditLogger) LogLogin(user, ip string, success bool)

LogLogin logs a login attempt per AI.md PART 11 line 11776

func (*AuditLogger) LogLoginFailed

func (l *AuditLogger) LogLoginFailed(user, ip, reason string)

LogLoginFailed logs a failed login attempt

func (*AuditLogger) LogLogout

func (l *AuditLogger) LogLogout(user, ip string)

LogLogout logs a logout per AI.md PART 11 line 11777

func (*AuditLogger) LogMaintenanceEntered

func (l *AuditLogger) LogMaintenanceEntered(actor, ip, reason string)

LogMaintenanceEntered logs entering maintenance mode

func (*AuditLogger) LogMaintenanceExited

func (l *AuditLogger) LogMaintenanceExited(actor, ip string)

LogMaintenanceExited logs exiting maintenance mode

func (*AuditLogger) LogPasswordChanged

func (l *AuditLogger) LogPasswordChanged(user, ip string, selfChange bool)

LogPasswordChanged logs password change

func (*AuditLogger) LogRateLimitExceeded

func (l *AuditLogger) LogRateLimitExceeded(ip, path string, limit int)

LogRateLimitExceeded logs rate limit exceeded

func (*AuditLogger) LogReload

func (l *AuditLogger) LogReload(user, ip string, success bool, details string)

LogReload logs a configuration reload

func (*AuditLogger) LogSMTPUpdated

func (l *AuditLogger) LogSMTPUpdated(actor, ip string)

LogSMTPUpdated logs SMTP configuration update

func (*AuditLogger) LogSSLUpdated

func (l *AuditLogger) LogSSLUpdated(actor, ip, domain string)

LogSSLUpdated logs SSL configuration update

func (*AuditLogger) LogSchedulerTaskFailed

func (l *AuditLogger) LogSchedulerTaskFailed(taskName, reason string)

LogSchedulerTaskFailed logs scheduler task failure

func (*AuditLogger) LogSchedulerTaskManualRun

func (l *AuditLogger) LogSchedulerTaskManualRun(actor, ip, taskName string, success bool)

LogSchedulerTaskManualRun logs manual scheduler task execution

func (*AuditLogger) LogServerStarted

func (l *AuditLogger) LogServerStarted(version, nodeID string)

LogServerStarted logs server startup

func (*AuditLogger) LogServerStopped

func (l *AuditLogger) LogServerStopped(reason, nodeID string)

LogServerStopped logs server shutdown

func (*AuditLogger) LogSessionExpired

func (l *AuditLogger) LogSessionExpired(user, ip, sessionID string)

LogSessionExpired logs session expiration

func (*AuditLogger) LogSessionRevoked

func (l *AuditLogger) LogSessionRevoked(actor, ip, targetUser, sessionID string)

LogSessionRevoked logs session revocation

func (*AuditLogger) LogTokenCreate

func (l *AuditLogger) LogTokenCreate(user, ip, tokenName string)

LogTokenCreate logs a token creation per AI.md PART 11 line 11916

func (*AuditLogger) LogTokenRegenerated

func (l *AuditLogger) LogTokenRegenerated(user, ip, tokenName string)

LogTokenRegenerated logs API token regeneration

func (*AuditLogger) LogTokenRevoke

func (l *AuditLogger) LogTokenRevoke(user, ip, tokenName string)

LogTokenRevoke logs a token revocation per AI.md PART 11 line 11917

func (*AuditLogger) LogUserCreate

func (l *AuditLogger) LogUserCreate(actor, ip, targetUser string)

LogUserCreate logs a user creation per AI.md PART 11 line 11796

func (*AuditLogger) LogUserDelete

func (l *AuditLogger) LogUserDelete(actor, ip, targetUser string)

LogUserDelete logs a user deletion per AI.md PART 11 line 11797

func (*AuditLogger) LogUserRoleChanged

func (l *AuditLogger) LogUserRoleChanged(actor, ip, targetUser, oldRole, newRole string)

LogUserRoleChanged logs user role change

func (*AuditLogger) LogUserSuspended

func (l *AuditLogger) LogUserSuspended(actor, ip, targetUser, reason string)

LogUserSuspended logs user suspension

func (*AuditLogger) LogUserUnsuspended

func (l *AuditLogger) LogUserUnsuspended(actor, ip, targetUser string)

LogUserUnsuspended logs user unsuspension

func (*AuditLogger) QueryAuditLogs

func (l *AuditLogger) QueryAuditLogs(opts AuditQueryOptions) (*AuditQueryResult, error)

QueryAuditLogs queries audit logs with filtering options Reads the audit log file and returns matching entries

func (*AuditLogger) Rotate

func (l *AuditLogger) Rotate() error

Rotate rotates the audit log file

type AuditQueryOptions

type AuditQueryOptions struct {
	// Filter by category (authentication, admin, configuration, etc.)
	Category AuditCategory
	// Filter by event type (admin.login, user.created, etc.)
	Event AuditAction
	// Filter by actor username
	ActorUsername string
	// Filter by actor IP
	ActorIP string
	// Filter by target type
	TargetType string
	// Filter by target name
	TargetName string
	// Filter by result (success/failure)
	Result string
	// Filter by severity
	Severity AuditSeverity
	// Start time for range query (inclusive)
	StartTime time.Time
	// End time for range query (inclusive)
	EndTime time.Time
	// Maximum number of entries to return (0 = unlimited)
	Limit int
	// Number of entries to skip (for pagination)
	Offset int
}

AuditQueryOptions defines filtering options for querying audit logs

type AuditQueryResult

type AuditQueryResult struct {
	// Total number of matching entries (before limit/offset)
	Total int `json:"total"`
	// Number of entries returned
	Count int `json:"count"`
	// The audit entries
	Entries []AuditEntry `json:"entries"`
	// Query duration in milliseconds
	DurationMs int64 `json:"duration_ms"`
}

AuditQueryResult contains the results of an audit log query

type AuditRetentionPolicy

type AuditRetentionPolicy struct {
	// Maximum age of audit entries (0 = no limit)
	MaxAge time.Duration
	// Maximum number of entries to keep (0 = no limit)
	MaxEntries int
	// Keep critical events regardless of age
	PreserveCritical bool
}

AuditRetentionPolicy defines the retention policy for audit logs

func DefaultAuditRetentionPolicy

func DefaultAuditRetentionPolicy() AuditRetentionPolicy

DefaultAuditRetentionPolicy returns the default retention policy 90 days retention, no entry limit, preserve critical events

type AuditSeverity

type AuditSeverity string

AuditSeverity represents audit event severity per AI.md PART 11 lines 11998-12005

const (
	AuditSeverityInfo     AuditSeverity = "info"     // Successful normal operations
	AuditSeverityWarning  AuditSeverity = "warn"     // Failed attempts, recoverable issues
	AuditSeverityError    AuditSeverity = "error"    // Failures requiring attention
	AuditSeverityCritical AuditSeverity = "critical" // Security incidents, server failures
)

type AuditStats

type AuditStats struct {
	TotalEntries int                   `json:"total_entries"`
	OldestEntry  time.Time             `json:"oldest_entry"`
	NewestEntry  time.Time             `json:"newest_entry"`
	ByCategory   map[AuditCategory]int `json:"by_category"`
	BySeverity   map[AuditSeverity]int `json:"by_severity"`
	ByResult     map[string]int        `json:"by_result"`
}

AuditStats contains audit log statistics

type AuditTarget

type AuditTarget struct {
	Type string `json:"type"`           // Target type (session, user, config, token, etc.)
	ID   string `json:"id,omitempty"`   // Target ID
	Name string `json:"name,omitempty"` // Target name
}

AuditTarget represents what the action was performed on per AI.md PART 11

type DebugEntry

type DebugEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	File      string                 `json:"file,omitempty"`
	Line      int                    `json:"line,omitempty"`
	Function  string                 `json:"function,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

DebugEntry represents a debug log entry

type DebugLogger

type DebugLogger struct {
	// contains filtered or unexported fields
}

DebugLogger logs debug messages to debug.log

func NewDebugLogger

func NewDebugLogger(path string) *DebugLogger

NewDebugLogger creates a new debug logger

func (*DebugLogger) Close

func (l *DebugLogger) Close() error

Close closes the debug logger

func (*DebugLogger) Debug

func (l *DebugLogger) Debug(msg string, fields ...map[string]interface{})

Debug logs a debug message

func (*DebugLogger) DebugWithCaller

func (l *DebugLogger) DebugWithCaller(msg string, file string, line int, function string, fields ...map[string]interface{})

DebugWithCaller logs a debug message with caller info

func (*DebugLogger) Disable

func (l *DebugLogger) Disable()

Disable disables the debug logger and closes the file

func (*DebugLogger) Enable

func (l *DebugLogger) Enable()

Enable enables the debug logger and opens the file

func (*DebugLogger) IsEnabled

func (l *DebugLogger) IsEnabled() bool

IsEnabled returns whether debug logging is enabled

func (*DebugLogger) Log

func (l *DebugLogger) Log(entry DebugEntry)

Log logs a debug entry

func (*DebugLogger) Rotate

func (l *DebugLogger) Rotate() error

Rotate rotates the debug log file

func (*DebugLogger) SetFormat

func (l *DebugLogger) SetFormat(format string)

SetFormat sets the log format

func (*DebugLogger) SetStdout

func (l *DebugLogger) SetStdout(enabled bool)

SetStdout enables/disables stdout output

func (*DebugLogger) Trace

func (l *DebugLogger) Trace(msg string, fields ...map[string]interface{})

Trace logs a trace-level debug message

type ErrorEntry

type ErrorEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Error     string                 `json:"error,omitempty"`
	File      string                 `json:"file,omitempty"`
	Line      int                    `json:"line,omitempty"`
	Stack     string                 `json:"stack,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

ErrorEntry represents an error log entry

type ErrorLogger

type ErrorLogger struct {
	// contains filtered or unexported fields
}

ErrorLogger logs error messages to error.log

func NewErrorLogger

func NewErrorLogger(path string) *ErrorLogger

NewErrorLogger creates a new error logger

func (*ErrorLogger) Close

func (l *ErrorLogger) Close() error

Close closes the error logger

func (*ErrorLogger) Error

func (l *ErrorLogger) Error(msg string, err error, fields ...map[string]interface{})

Error logs an error message

func (*ErrorLogger) ErrorWithStack

func (l *ErrorLogger) ErrorWithStack(msg string, err error, stack string, fields ...map[string]interface{})

ErrorWithStack logs an error with stack trace

func (*ErrorLogger) Fatal

func (l *ErrorLogger) Fatal(msg string, err error, fields ...map[string]interface{})

Fatal logs a fatal error

func (*ErrorLogger) Log

func (l *ErrorLogger) Log(entry ErrorEntry)

Log logs an error entry

func (*ErrorLogger) Rotate

func (l *ErrorLogger) Rotate() error

Rotate rotates the error log file

func (*ErrorLogger) SetFormat

func (l *ErrorLogger) SetFormat(format string)

SetFormat sets the log format

func (*ErrorLogger) SetStdout

func (l *ErrorLogger) SetStdout(enabled bool)

SetStdout enables/disables stdout output

type FormatVariable

type FormatVariable struct {
	Name        string
	Description string
	Example     string
}

FormatVariable represents a log format variable

type LineScanner

type LineScanner struct {
	// contains filtered or unexported fields
}

LineScanner wraps bufio.Scanner for reading lines

func NewLineScanner

func NewLineScanner(r io.Reader) *LineScanner

NewLineScanner creates a new line scanner

func (*LineScanner) Err

func (s *LineScanner) Err() error

Err returns any scanning error

func (*LineScanner) Scan

func (s *LineScanner) Scan() bool

Scan advances the scanner

func (*LineScanner) Text

func (s *LineScanner) Text() string

Text returns the current line

type LogLevel

type LogLevel int

LogLevel represents log severity

const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

func (LogLevel) String

func (l LogLevel) String() string

type LogType

type LogType string

LogType represents different log types

const (
	LogTypeAccess   LogType = "access"
	LogTypeServer   LogType = "server"
	LogTypeError    LogType = "error"
	LogTypeSecurity LogType = "security"
	LogTypeAudit    LogType = "audit"
	LogTypeDebug    LogType = "debug"
)

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager manages all log types

func NewManager

func NewManager(logDir string) *Manager

NewManager creates a new logging manager

func (*Manager) Access

func (m *Manager) Access() *AccessLogger

Access returns the access logger

func (*Manager) Audit

func (m *Manager) Audit() *AuditLogger

Audit returns the audit logger

func (*Manager) Close

func (m *Manager) Close() error

Close closes all loggers

func (*Manager) Debug

func (m *Manager) Debug() *DebugLogger

Debug returns the debug logger

func (*Manager) Error

func (m *Manager) Error() *ErrorLogger

Error returns the error logger

func (*Manager) RotateAll

func (m *Manager) RotateAll() error

RotateAll rotates all log files

func (*Manager) Security

func (m *Manager) Security() *SecurityLogger

Security returns the security logger

func (*Manager) Server

func (m *Manager) Server() *ServerLogger

Server returns the server logger

type SecurityEntry

type SecurityEntry struct {
	Timestamp time.Time     `json:"timestamp"`
	Event     SecurityEvent `json:"event"`
	IP        string        `json:"ip"`
	User      string        `json:"user,omitempty"`
	Path      string        `json:"path,omitempty"`
	Details   string        `json:"details,omitempty"`
}

SecurityEntry represents a security log entry

type SecurityEvent

type SecurityEvent string

SecurityEvent represents a security event type

const (
	SecurityEventLoginFailed   SecurityEvent = "LOGIN_FAILED"
	SecurityEventLoginSuccess  SecurityEvent = "LOGIN_SUCCESS"
	SecurityEventRateLimited   SecurityEvent = "RATE_LIMITED"
	SecurityEventBlocked       SecurityEvent = "BLOCKED"
	SecurityEventSuspicious    SecurityEvent = "SUSPICIOUS"
	SecurityEventBruteForce    SecurityEvent = "BRUTE_FORCE"
	SecurityEventInvalidToken  SecurityEvent = "INVALID_TOKEN"
	SecurityEventCSRFViolation SecurityEvent = "CSRF_VIOLATION"
)

type SecurityLogger

type SecurityLogger struct {
	// contains filtered or unexported fields
}

SecurityLogger logs security events (fail2ban compatible)

func NewSecurityLogger

func NewSecurityLogger(path string) *SecurityLogger

NewSecurityLogger creates a new security logger

func (*SecurityLogger) Close

func (l *SecurityLogger) Close() error

Close closes the security logger

func (*SecurityLogger) Log

func (l *SecurityLogger) Log(entry SecurityEntry)

Log logs a security event

func (*SecurityLogger) LogBlocked

func (l *SecurityLogger) LogBlocked(ip, path, reason string)

LogBlocked logs a blocked request

func (*SecurityLogger) LogBruteForce

func (l *SecurityLogger) LogBruteForce(ip, path string, attempts int)

LogBruteForce logs a brute force detection

func (*SecurityLogger) LogCSRFViolation

func (l *SecurityLogger) LogCSRFViolation(ip, path string)

LogCSRFViolation logs a CSRF violation

func (*SecurityLogger) LogInvalidToken

func (l *SecurityLogger) LogInvalidToken(ip, path string)

LogInvalidToken logs an invalid token attempt

func (*SecurityLogger) LogLoginFailed

func (l *SecurityLogger) LogLoginFailed(ip, user, path string)

LogLoginFailed logs a failed login attempt

func (*SecurityLogger) LogLoginSuccess

func (l *SecurityLogger) LogLoginSuccess(ip, user string)

LogLoginSuccess logs a successful login

func (*SecurityLogger) LogRateLimited

func (l *SecurityLogger) LogRateLimited(ip, path string)

LogRateLimited logs a rate limit event

func (*SecurityLogger) LogSuspicious

func (l *SecurityLogger) LogSuspicious(ip, path, details string)

LogSuspicious logs a suspicious activity

func (*SecurityLogger) Rotate

func (l *SecurityLogger) Rotate() error

Rotate rotates the security log file

type ServerEntry

type ServerEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

ServerEntry represents a server log entry

type ServerLogger

type ServerLogger struct {
	// contains filtered or unexported fields
}

ServerLogger logs application events

func NewServerLogger

func NewServerLogger(path string) *ServerLogger

NewServerLogger creates a new server logger

func (*ServerLogger) Close

func (l *ServerLogger) Close() error

Close closes the server logger

func (*ServerLogger) Debug

func (l *ServerLogger) Debug(msg string, fields ...map[string]interface{})

Debug logs a debug message

func (*ServerLogger) Error

func (l *ServerLogger) Error(msg string, fields ...map[string]interface{})

Error logs an error message

func (*ServerLogger) Fatal

func (l *ServerLogger) Fatal(msg string, fields ...map[string]interface{})

Fatal logs a fatal message and exits

func (*ServerLogger) Info

func (l *ServerLogger) Info(msg string, fields ...map[string]interface{})

Info logs an info message

func (*ServerLogger) Rotate

func (l *ServerLogger) Rotate() error

Rotate rotates the server log file

func (*ServerLogger) SetFormat

func (l *ServerLogger) SetFormat(format string)

SetFormat sets the log format

func (*ServerLogger) SetLevel

func (l *ServerLogger) SetLevel(level LogLevel)

SetLevel sets the minimum log level

func (*ServerLogger) SetStdout

func (l *ServerLogger) SetStdout(enabled bool)

SetStdout enables/disables stdout output

func (*ServerLogger) Warn

func (l *ServerLogger) Warn(msg string, fields ...map[string]interface{})

Warn logs a warning message

func (*ServerLogger) Writer

func (l *ServerLogger) Writer() io.Writer

Writer returns an io.Writer for use with standard log

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL