cclogger

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 4 Imported by: 10

README

ccLogger Interface

The ccLogger component provides a unified logging interface for ClusterCockpit applications. It wraps Go's standard log package with support for multiple log levels and integrates seamlessly with systemd's journaling system.

Features

  • Multiple log levels: debug, info, warn, error, critical
  • Systemd integration: Uses systemd priority prefixes for proper log categorization
  • Flexible output: Log to stderr (default), files, or custom writers
  • Thread-safe: All logging functions are safe for concurrent use
  • Component tagging: Built-in support for component-specific logging
  • Formatted and unformatted logging: Choose between simple or printf-style logging

Quick Start

import "github.com/ClusterCockpit/cc-lib/ccLogger"

func main() {
    // Initialize with log level and timestamp preference
    cclogger.Init("info", false) // info level, no timestamps (systemd adds them)
    
    // Log messages
    cclogger.Info("Application started")
    cclogger.Warnf("Configuration file %s not found, using defaults", configPath)
    cclogger.Error("Failed to connect to database")
}

Log Levels

Log levels in order of increasing severity:

Level Use Case Example
debug Detailed development/troubleshooting information cclogger.Debug("Processing item 42")
info General informational messages cclogger.Info("Server started on port 8080")
warn Important but non-critical issues cclogger.Warn("Cache miss, fetching from database")
err/fatal Errors that allow continued execution cclogger.Error("Failed to send email notification")
crit Critical errors leading to termination cclogger.Fatal("Cannot bind to port 8080") (exits)
Setting Log Level

When you initialize cclogger with a specific level, only messages at that level and above are displayed:

cclogger.Init("warn", false)
// Now only warn, error, and critical messages are shown
// Debug and info messages are suppressed

Basic Usage

Simple Logging
cclogger.Debug("Detailed debug information")
cclogger.Info("User logged in successfully")
cclogger.Warn("Retry attempt 3 of 5")
cclogger.Error("Database query failed")
cclogger.Fatal("Critical error, exiting") // Exits with code 1
Formatted Logging

Use printf-style formatting for structured output:

cclogger.Debugf("Processing item %d of %d", current, total)
cclogger.Infof("User %s logged in from %s", username, ipAddress)
cclogger.Warnf("Cache size %d MB exceeds threshold %d MB", size, threshold)
cclogger.Errorf("Failed to open file %s: %v", filename, err)
Component Logging

Tag log messages with component names for better organization:

cclogger.ComponentInfo("scheduler", "Job queue initialized")
cclogger.ComponentError("database", "Connection pool exhausted")
cclogger.ComponentWarn("auth", "Failed login attempt from", ipAddr)
cclogger.ComponentDebug("cache", "Cache hit rate:", hitRate)

Advanced Usage

Logging to Files

Redirect logs to a file for specific levels:

// Log warn, info, and debug to file
// Error and critical still go to stderr
cclogger.SetOutputFile("warn", "/var/log/myapp.log")

Note: The file remains open for the lifetime of the application. This is intentional to allow continuous logging.

Timestamps

Control timestamp inclusion based on your environment:

// No timestamps (recommended for systemd)
cclogger.Init("info", false)

// With timestamps (for traditional logging)
cclogger.Init("info", true)
Custom Writers

You can customize output destinations by modifying the writers before initialization:

import "os"

// Direct debug logs to a custom writer
cclogger.DebugWriter = myCustomWriter
cclogger.Init("debug", false)

Systemd Integration

ccLogger uses systemd's priority prefixes to enable proper log categorization in journald:

  • <7> - Debug (LOG_DEBUG)
  • <6> - Info (LOG_INFO)
  • <4> - Warning (LOG_WARNING)
  • <3> - Error (LOG_ERR)
  • <2> - Critical (LOG_CRIT)

When running under systemd, these prefixes allow journald to automatically:

  • Filter logs by priority
  • Add metadata (timestamps, service name, etc.)
  • Enable structured querying with journalctl

Example journalctl usage:

# View only warning and above
journalctl -u myservice -p warning

# View logs from specific component (if using ComponentInfo etc.)
journalctl -u myservice | grep '\[scheduler\]'

Best Practices

  1. Choose the right level:

    • Use Debug for verbose diagnostic information
    • Use Info for normal application flow events
    • Use Warn for unusual but handled situations
    • Use Error for failures that don't stop the application
    • Use Fatal only for unrecoverable errors
  2. Disable timestamps for systemd: When running as a systemd service, use Init(level, false) to avoid duplicate timestamps

  3. Use component logging: For multi-component applications, use Component* functions to make log filtering easier

  4. Structured logging: Use formatted variants (*f functions) to create parseable log messages:

    cclogger.Infof("user=%s action=%s status=%s", user, action, status)
    
  5. Thread safety: All logging functions are thread-safe, so you can safely log from goroutines

  6. Error context: Always include relevant context in error messages:

    cclogger.Errorf("Failed to connect to %s:%d: %v", host, port, err)
    

API Reference

For complete API documentation, see the package documentation or run:

go doc github.com/ClusterCockpit/cc-lib/ccLogger

Examples

Basic Application
package main

import "github.com/ClusterCockpit/cc-lib/ccLogger"

func main() {
    cclogger.Init("info", false)
    
    cclogger.Info("Application starting")
    
    if err := doSomething(); err != nil {
        cclogger.Errorf("Operation failed: %v", err)
        return
    }
    
    cclogger.Info("Application completed successfully")
}
Multi-Component Service
func startScheduler() {
    cclogger.ComponentInfo("scheduler", "Starting job scheduler")
    
    for job := range jobQueue {
        cclogger.ComponentDebug("scheduler", "Processing job", job.ID)
        
        if err := processJob(job); err != nil {
            cclogger.ComponentError("scheduler", "Job failed:", job.ID, err)
        }
    }
}

func connectDatabase() error {
    cclogger.ComponentInfo("database", "Connecting to database")
    
    if err := db.Connect(); err != nil {
        cclogger.ComponentError("database", "Connection failed:", err)
        return err
    }
    
    cclogger.ComponentInfo("database", "Connected successfully")
    return nil
}

Documentation

Overview

Package cclogger implements a simple log wrapper for the standard log package.

cclogger provides a simple way of logging with different levels (debug, info, warn, error, critical). It integrates with systemd's journaling system by using standard systemd log level prefixes.

Log Levels

The package supports the following log levels in order of increasing severity:

  • debug: Detailed information for development and troubleshooting
  • info: General informational messages about application progress
  • warn: Warning messages for important but non-critical issues
  • err/fatal: Error messages for failures that may allow continued execution
  • crit: Critical errors that typically result in program termination

Basic Usage

Initialize the logger with a log level and optional timestamp:

cclogger.Init("info", false) // info level, no timestamps (systemd adds them)

Log messages using level-specific functions:

cclogger.Debug("Detailed debug information")
cclogger.Info("Application started")
cclogger.Warn("Configuration value missing, using default")
cclogger.Error("Failed to connect to database")
cclogger.Fatal("Critical error, exiting") // exits with code 1

Use formatted variants for structured output:

cclogger.Infof("Processing %d items", count)
cclogger.Errorf("Failed to open file: %v", err)

Component Logging

For component-specific logging, use the Component* variants:

cclogger.ComponentInfo("scheduler", "Job submitted successfully")
cclogger.ComponentError("database", "Connection pool exhausted")

Thread Safety

All logging functions are thread-safe as they use the standard library's log.Logger, which is safe for concurrent use.

Systemd Integration

Log messages use systemd's priority prefixes (<7> for debug, <6> for info, etc.) which allows systemd-journald to properly categorize log entries. When running under systemd, timestamps can be omitted (logdate=false) as journald adds them.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DebugWriter is the output destination for debug-level logs
	DebugWriter io.Writer = os.Stderr
	// InfoWriter is the output destination for info-level logs
	InfoWriter io.Writer = os.Stderr
	// WarnWriter is the output destination for warning-level logs
	WarnWriter io.Writer = os.Stderr
	// ErrWriter is the output destination for error-level logs
	ErrWriter io.Writer = os.Stderr
	// CritWriter is the output destination for critical-level logs
	CritWriter io.Writer = os.Stderr
)

Package-level writers for each log level. These can be configured to direct output to different destinations. By default, all output goes to stderr. When Init() is called with a log level, writers for levels below the threshold are set to io.Discard to suppress output.

View Source
var (
	// DebugPrefix is the prefix for debug-level log messages (systemd priority 7)
	DebugPrefix string = "<7>[DEBUG]    "
	// InfoPrefix is the prefix for info-level log messages (systemd priority 6)
	InfoPrefix string = "<6>[INFO]     "
	// WarnPrefix is the prefix for warning-level log messages (systemd priority 4)
	WarnPrefix string = "<4>[WARNING]  "
	// ErrPrefix is the prefix for error-level log messages (systemd priority 3)
	ErrPrefix string = "<3>[ERROR]    "
	// CritPrefix is the prefix for critical-level log messages (systemd priority 2)
	CritPrefix string = "<2>[CRITICAL] "
)

Log level prefixes using systemd priority levels. The numeric prefix (<N>) corresponds to syslog/systemd severity levels:

<7> = Debug, <6> = Informational, <4> = Warning, <3> = Error, <2> = Critical

See: https://www.freedesktop.org/software/systemd/man/sd-daemon.html

View Source
var (
	// DebugLog is the logger instance for debug-level messages
	DebugLog *log.Logger = log.New(DebugWriter, DebugPrefix, log.LstdFlags)
	// InfoLog is the logger instance for info-level messages
	InfoLog *log.Logger = log.New(InfoWriter, InfoPrefix, log.LstdFlags|log.Lshortfile)
	// WarnLog is the logger instance for warning-level messages
	WarnLog *log.Logger = log.New(WarnWriter, WarnPrefix, log.LstdFlags|log.Lshortfile)
	// ErrLog is the logger instance for error-level messages
	ErrLog *log.Logger = log.New(ErrWriter, ErrPrefix, log.LstdFlags|log.Llongfile)
	// CritLog is the logger instance for critical-level messages
	CritLog *log.Logger = log.New(CritWriter, CritPrefix, log.LstdFlags|log.Llongfile)
)

Package-level logger instances for each log level. These are configured by Init() with appropriate flags and output destinations. Debug logs show no file info, Info/Warn show short file:line, Error/Crit show full path.

Functions

func Abort

func Abort(v ...any)

Abort logs to STDOUT without string formatting; application exits with error code 1. Used for terminating with message after to be expected errors, e.g. wrong arguments or during init().

func Abortf

func Abortf(format string, v ...any)

Abortf logs to STDOUT with string formatting; application exits with error code 1. Used for terminating with message after to be expected errors, e.g. wrong arguments or during init().

func ComponentDebug

func ComponentDebug(component string, v ...any)

ComponentDebug logs to DEBUG writer with a component prefix; application continues.

func ComponentError

func ComponentError(component string, v ...any)

ComponentError logs to ERROR writer with a component prefix; application continues.

func ComponentInfo added in v0.2.0

func ComponentInfo(component string, v ...any)

ComponentInfo logs to INFO writer with a component prefix; application continues.

func ComponentPrint

func ComponentPrint(component string, v ...any)

ComponentPrint logs to INFO writer with a component prefix; application continues.

func ComponentWarn added in v0.2.0

func ComponentWarn(component string, v ...any)

ComponentWarn logs to WARNING writer with a component prefix; application continues.

func Debug

func Debug(v ...any)

Debug logs to DEBUG writer without string formatting; application continues. Used for logging additional information, primarily for development.

func Debugf

func Debugf(format string, v ...any)

Debugf logs to DEBUG writer with string formatting; application continues. Used for logging additional information, primarily for development.

func Error

func Error(v ...any)

Error logs to ERROR writer without string formatting; application continues. Used for logging errors, but code still can return default(s) or nil.

func Errorf

func Errorf(format string, v ...any)

Errorf logs to ERROR writer with string formatting; application continues. Used for logging errors, but code still can return default(s) or nil.

func Exit

func Exit(v ...any)

Exit logs to STDOUT without string formatting; application exits with error code 0. Used for exiting succesfully with message after expected outcome, e.g. successful single-call application runs.

func Exitf

func Exitf(format string, v ...any)

Exitf logs to STDOUT with string formatting; application exits with error code 0. Used for exiting succesfully with message after expected outcome, e.g. successful single-call application runs.

func Fatal

func Fatal(v ...any)

Fatal writes to CRITICAL writer without string formatting; application exits with error code 1. Used for terminating on unexpected errors with date and code location.

func Fatalf

func Fatalf(format string, v ...any)

Fatalf logs to CRITICAL writer with string formatting; application exits with error code 1. Used for terminating on unexpected errors with date and code location.

func Info

func Info(v ...any)

Info logs to INFO writer without string formatting; application continues. Used for logging additional information, e.g. notable returns or common fail-cases.

func Infof

func Infof(format string, v ...any)

Infof log to INFO writer with string formatting; application continues. Used for logging additional information, e.g. notable returns or common fail-cases.

func Init

func Init(lvl string, logdate bool)

Init initializes cclogger with the specified log level and timestamp configuration.

The lvl parameter accepts the following values:

  • "debug": Show all log messages
  • "info": Show info, warn, err, and crit messages (suppress debug)
  • "warn": Show warn, err, and crit messages (suppress info and debug)
  • "err" or "fatal": Show err and crit messages (suppress warn, info, and debug)
  • "crit": Show only crit messages (suppress all others)

If an invalid level is provided, all levels will be enabled (debug mode) and a warning will be logged.

The logdate parameter controls timestamp inclusion:

  • false: No timestamps (recommended when running under systemd, as journald adds timestamps)
  • true: Include date and time in log output

Example:

cclogger.Init("info", false) // Show info and above, no timestamps

func Loglevel

func Loglevel() string

Loglevel returns the current loglevel

func Panic

func Panic(v ...any)

Panic logs to PANIC function without string formatting; application exits with panic. Used for terminating on unexpected errors with stacktrace.

func Panicf

func Panicf(format string, v ...any)

Panicf logs to PANIC function with string formatting; application exits with panic. Used for terminating on unexpected errors with stacktrace.

func Print

func Print(v ...any)

Print logs to STDOUT without string formatting; application continues. Used for special cases not requiring log information like date or location.

func Printf

func Printf(format string, v ...any)

Printf logs to STDOUT with string formatting; application continues. Used for special cases not requiring log information like date or location.

func SetOutputFile added in v0.2.0

func SetOutputFile(lvl string, logfile string)

SetOutputFile redirects log output to a file for the specified level and all lower levels.

The lvl parameter determines which loggers write to the file:

  • "debug": Only debug logs go to file
  • "info": Info and debug logs go to file
  • "warn": Warn, info, and debug logs go to file
  • "err" or "fatal": Error, warn, info, and debug logs go to file
  • "crit": All logs go to file

The file is opened in append mode and created if it doesn't exist. The file remains open for the lifetime of the loggers.

WARNING: This function does not close the file after setting it as output. The file will remain open until the program exits. This is intentional to allow continued logging to the file.

Example:

cclogger.SetOutputFile("warn", "/var/log/myapp.log")
// Now warn, info, and debug logs write to the file
// Error and critical logs still go to their default writers (stderr)

func Warn

func Warn(v ...any)

Warn logs to WARNING writer without string formatting; application continues. Used for logging important information, e.g. uncommon edge-cases or administration related information.

func Warnf

func Warnf(format string, v ...any)

Warnf logs to WARNING writer with string formatting; application continues. Used for logging important information, e.g. uncommon edge-cases or administration related information.

Types

This section is empty.

Jump to

Keyboard shortcuts

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