szlog

package module
v0.0.15 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2025 License: GPL-3.0 Imports: 10 Imported by: 2

README

Package szlog

package szlog

Package szlog is a flexible output and logging library for Go. It builds on the standard log while adding:

  • six standard logging levels for categorizing messages by severity (Fatal, Error, Warn, Info, Debug, Trace with Fatalf, Errorf, Warnf, Infof, Debugf, Tracef for formatting) layered on top of the standard log package

  • six independent verbosity levels (Say0–Say5 with Say0f–Say5f for formatting)

  • lazy evaluation with func() DEFER so expensive values are only computed when needed

  • efficient function swapping so disabled functions are minimal

  • local formatting through the Go text package by setting a locale string ("en", "en-CA", "fr", etc.)

Overview

A lightweight logging and verbosity framework for Go that extends the standard library with structured levels, verbosity control, and deferred evaluation. Logging levels target structured diagnostic messages, while verbosity levels are designed for user-facing or progress output

Each output function is a variable member that may be swapped at runtime. When disabled, a function is replaced with a no-op and incurs minimal runtime cost. When enabled, the function points to an optimized writer. Each function mirrors standard fmt and log package function Print and Printf. Two versions of each function is supplied with long and short identifiers.

It further offers two ways to output messages. For full control, create a *Log instance with New(), giving you an independent logger with its own output, levels, and settings. For quick and convenient logging, use the package-level functions (Info, Error, Warn, etc.), which operate through a default internal logger automatically created for you. Both provide the same API; choose instance-based loggers when you need separate configurations, or rely on the package-level functions for simple, global logging.

An instance can be created as follows:


// New returns a new Log instance with default settings.
func New() *Log

While any instance or the default inner log can be reset to initial conditions with the Reset method as follows:


// Reset restores all log settings to their default values.
func (l *Log) Reset()
func Reset()

The builtin default logger may be accessed/replaced with:


// Default returns the package's current default logger.
func Default() *Log

// SetDefault replaces the package's default logger with the provided one.
// It returns the previous default logger.
func SetDefault(newDefaultLog *Log) *Log

Logging Levels

Logging functions categorize messages by severity writing to the standard go supplied log package. These functions report plain or formatted diagnostic and status messages:

+-----------+----------------+-----------------------------------------+
| Level     | Functions      | Description                             |
+-----------+----------------+-----------------------------------------+
| Fatal     | F, Fatal       | Plain Critical Errors, program exits    |
|           | Ff, Fatalf     | Formatted Critical Errors, program exits|
| Error     | E, Error       | Plain errors that allow continuation    |
|           | Ef, Errorf     | Formatted errors that allow continuation|
| Warn      | W, Warn        | Plain warnings needing attention        |
|           | Wf, Warnf      | Formatted warnings needing attention    |
| Info      | I, Info        | Plain progress and status info          |
|           | If, Infof      | Formatted progress and status info      |
| Debug     | D, Debug       | Plain developer-focused diagnostics     |
|           | Df, Debugf     | Formatted developer-focused diagnostics |
| Trace     | T, Trace       | Plain detailed program flow             |
|           | Tf, Tracef     | Formatted detailed program flow         |
+-----------+----------------+-----------------------------------------+
Verbose Output Levels

Verbosity output is completely separate from logging providing 5 levels of plain or formatted messages in addition to normal program output.

The verbose output functions provide fine-grained control over program messaging through six levels: Say0…Say5 and their formatted counterparts Say0f…Say5f. Level 0 represents the default program output, active when no verbosity flags are given or when explicitly set with SetVerbose(0). Increasing levels (1–5) are enabled by supplying additional verbosity flags or calling SetVerbose(1..5), progressively revealing more detailed output. All verbose functions respect the global setting: output is suppressed entirely when --quiet is specified or SetVerbose(-1) is used, ensuring even default level 0 messages are silenced.

+-----------+----------------+-----------------------------------------+
| Level     | Functions      | Typical Use                             |
+-----------+----------------+-----------------------------------------+
| 0         | S0, Say0       | Plain normal program messages           |
|           | S0f, Say0f     | Formatted normal program messages       |
| 1         | S1, Say1       | Plain additional messages               |
|           | S1f, Say1f     | Formatted additional messages           |
| 2         | S2, Say2       | Plain moderate detailed messages        |
|           | S2f, Say2f     | Formatted moderate detailed messages    |
| 3         | S3, Say3       | Plain detailed messages                 |
|           | S3f, Say3f     | Formatted detailed messages             |
| 4         | S4, Say4       | Plain highly detailed messages          |
|           | S4f, Say4f     | Formatted highly detailed messages      |
| 5         | S5, Say5       | Plain maximum verbosity                 |
|           | S5f, Say5f     | Formatted maximum verbosity             |
+-----------+----------------+-----------------------------------------+

Settings

Defaults

Settings have defaults which can be overridden by an environment variables.

+-------------+-------------+-------------------------------+
| Area        | Default     | Environment Variable Override |
|-------------|-------------|-------------------------------|
| LongLabels  | false       | SZLOG_LONG_LABELS             |
| LogLevel    | LevelError  | SZLOG_LEVEL                   |
| Language    | ""          | SZLOG_LANGUAGE                |
| Verbose     | 0           | SZLOG_VERBOSE                 |
+-------------+-------------+-------------------------------+
Command Line Arguments

Settings may also be specified in command line arguments

+-------------+-----------------------------------------------+
| Area        | Argument                                      |
|-------------|-----------------------------------------------|
| LongLabels  | --long-labels                                 |
| LogLevel    | --log <level>                                 |
| Language    | --language <local>                            |
| Verbose     | -v[v...] | --v[v...] | --verbose | --quiet    |
+-------------+-----------------------------------------------+

that are processed with the program functions:


// AbsorbArgs scans the provided argument list for enabled logging-related
// flags and updates the log configuration accordingly. Only arguments
// specified in the enable set are recognized; all others are ignored.
// Recognized flags are removed, and the cleaned argument slice is returned.
// Multiple `-v` flags increment verbosity, while invalid or conflicting
// combinations (e.g., `-v` with `--quiet`) return an error along with
// the original arguments. If no enable set is provided, EnableAll is used.
func (l *Log) AbsorbArgs(argsIn []string) ([]string, error)
func AbsorbArgs(argsIn []string) ([]string, error)

while usage information may be gathered with the program functions:


// ArgUsageInfo reports usage information for all enabled arguments by
// invoking the provided callback for each one. Only arguments permitted
// in the enable set are included, allowing applications to present
// accurate help/usage output tailored to their configuration.
func (l *Log) ArgUsageInfo(registerArgs func(string, string))
func ArgUsageInfo(registerArgs func(string, string))

Selective Argument Enabling

The AbsorbArgs function accepts an optional set of EnableArg constants to restrict which flags are recognized. This allows applications to individually enable or disable handling of built-in arguments. If no constants are provided, EnableAll is assumed.

+-----------------------|----------------------|-------------------------+
| Flag / Option         | `EnableArg` constant | Description             |
|-----------------------|----------------------|-------------------------|
| `-v`, `--verbose`     | `EnableVerbose`      | Increase verbosity      |
|                       |                      | (multiple `-v` allowed) |
| `--quiet`             | `EnableQuiet`        | Suppress output         |
| `--log <level>`       | `EnableLogLevel`     | Set log level (all,     |
|                       |                      | trace, debug, info,     |
|                       |                      | warn error, fatal,      |
|                       |                      | none)                   |
| `--language <locale>` | `EnableLanguage`     | Set message language    |
| `--long-labels`       | `EnableLongLabels`   | Use extended labels in  |
|                       |                      | log output              |
| *all of the above*    | `EnableAll`          | Default (recognize all  |
|                       |                      | arguments)              |
+-----------------------|----------------------|-------------------------+

Example usage:


// Only absorb verbosity and quiet flags, ignore all others.
args, err := szlog.AbsorbArgs(os.Args, EnableVerbose, EnableQuiet)

When to Disable Arguments

By default, szlog absorbs all supported flags. In some applications you may wish to disable certain arguments:

  • Custom flag parsing: If your program already defines --quiet or --log, you can prevent szlog from intercepting them by omitting EnableQuiet or EnableLogLevel.
  • Minimal CLI surface: Small utilities may only need -v for verbosity and want to skip everything else.
  • Conflict avoidance: If another library introduces overlapping flags, selectively enabling arguments avoids collisions.
  • Explicit control: Developers who prefer handling configuration programmatically can turn off all arguments and manage szlog options directly.

This flexibility ensures that szlog integrates smoothly with a variety of command-line setups without forcing a fixed argument model.

Program Functions

Finally settings man be queried and changed programmatically using library functions.

+-------------+--------------------------------------+
| Area        | Function(s)                          |
|-------------|--------------------------------------|
| Language    | Language()                           |
|             | SetLanguage(language string)         |
| LongLabels  | LongLabels()                         |
|             | SetLongLabels(enable bool)           |
| LogLevel    | Level()                              |
|             | SetLevel(newLogLevel LogLevel)       |
|             | SetCustomLevels(levels ...LogLevel)  |
| Verbose     | Verbose()                            |
|             | SetVerbose(level VerboseLevel)       |
+-------------+--------------------------------------+

implemented as follows:


// Language returns the current language setting used for localized formatting.
// An empty string indicates no localization is applied.
func (l *Log) Language() string
func Language() string

// SetLanguage updates the language used for localized formatting.
// Passing an empty string ("") disables localization. It returns any
// error encountered while setting the language.
func (l *Log) SetLanguage(langStr string) error
func SetLanguage(language string) error

// LongLabels reports whether long labels (FATAL, ERROR, WARN, INFO, DEBUG,
// TRACE) are currently enabled instead of their short forms (F, E, W, I, D,
// T).
func (l *Log) LongLabels() bool
func LongLabels() bool

// SetLongLabels enables or disables long labels in log output. When disabled,
// short labels (F, E, W, I, D, T) are used instead. It returns the previous
// setting.
func (l *Log) SetLongLabels(enable bool) bool
func SetLongLabels(enabled bool) bool

// Level reports the logger's current logging level.
func (l *Log) Level() LogLevel
func Level() LogLevel

// SetLevel updates the logger's logging level. Valid values include
// LevelNone, LevelFatal, LevelError, LevelWarn, LevelInfo, LevelDebug,
// LevelTrace, and LevelAll.
func (l *Log) SetLevel(newLogLevel LogLevel) LogLevel
func SetLevel(newLogLevel LogLevel) LogLevel

// SetCustomLevels enables a custom combination of individual levels.
// LevelNone, LevelAll, and LevelCustom are ignored. Internally, this
// always results in LevelCustom being applied.
func (l *Log) SetCustomLevels(levels ...LogLevel) LogLevel
func SetCustomLevels(levels ...LogLevel) LogLevel

// Verbose reports the logger's current verbosity level.
func (l *Log) Verbose() VerboseLevel
func Verbose() VerboseLevel

// SetVerbose adjusts the verbosity level (-1 through 5). Level -1 silences
// all output, while higher levels progressively enable more detail.
func (l *Log) SetVerbose(newLevel VerboseLevel) VerboseLevel
func SetVerbose(level VerboseLevel) VerboseLevel

Deferred Evaluation

Output function arguments can be wrapped in a func() DEFER, where DEFER is a string type. Deferred functions are only invoked if the target output function is enabled. This avoids the cost of constructing expensive strings or reports that would otherwise be discarded.

This pattern makes it safe to pass in expensive computations without worrying about wasted work if the message is suppressed.


    szlog.Info("Report:\n", func() szlog.DEFER {
      return generateReport()
    })

If Info logging is disabled, generateReport is never executed.

Localization

Szlog can bind to the Go text package for message localization. SetLanguage accepts a locale string such as "en" or "fr" to select the appropriate translation.

Convenience Function(s)


// Close is a convenience method for safely closing any io.Closer. If an error
// except os.ErrClosed (already closed) occurs during Close, it is logged as a
// warning. This method is primarily intended for use in insurance defer
// statements.
func (l *Log) Close(area string, closeable io.Closer)
func Close(area string, closeable io.Closer)

Use Cases

  • Use logging functions for structured severity-based output.
  • Use verbosity functions for progress and detailed tracing independent of logging configuration.
  • Combine deferred evaluation with either system for maximum performance.
Quick Start

    import "github.com/dancsecs/szlog"

    func main() {
      var configFileName string

      args,err:= szlog.AbsorbArgs(os.args,nil) // Set verbose and log level.

      if len(args) != 2 {  // Ignore extra args.
        configFileName = "default.cfg
      } else {
        configFileName = args[1]
      }

      szlog.Info("Application starting\n")

      szlog.Say0f("Processing configuration: %s\n",configFileName)

      szlog.Info("Report:\n", func() szlog.DEFER {
        return longRunningReport()
      })
    }

NOTE: If Info logging is disabled, longRunningReport() is never executed.


Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.


NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.

Documentation

Overview

Package szlog is a flexible output and logging library for Go. It builds on the standard log while adding:

  • six standard logging levels for categorizing messages by severity (Fatal, Error, Warn, Info, Debug, Trace with Fatalf, Errorf, Warnf, Infof, Debugf, Tracef for formatting) layered on top of the standard log package

  • six independent verbosity levels (Say0–Say5 with Say0f–Say5f for formatting)

  • lazy evaluation with `func() DEFER` so expensive values are only computed when needed

  • efficient function swapping so disabled functions are minimal

  • local formatting through the Go text package by setting a locale string ("en", "en-CA", "fr", etc.)

## Overview

A lightweight logging and verbosity framework for Go that extends the standard library with structured levels, verbosity control, and deferred evaluation. Logging levels target structured diagnostic messages, while verbosity levels are designed for user-facing or progress output

Each output function is a variable member that may be swapped at runtime. When disabled, a function is replaced with a no-op and incurs minimal runtime cost. When enabled, the function points to an optimized writer. Each function mirrors standard fmt and log package function Print and Printf. Two versions of each function is supplied with long and short identifiers.

It further offers two ways to output messages. For full control, create a *Log instance with New(), giving you an independent logger with its own output, levels, and settings. For quick and convenient logging, use the package-level functions (Info, Error, Warn, etc.), which operate through a default internal logger automatically created for you. Both provide the same API; choose instance-based loggers when you need separate configurations, or rely on the package-level functions for simple, global logging.

An instance can be created as follows:

```go

// New returns a new Log instance with default settings. func New() *Log

```

While any instance or the default inner log can be reset to initial conditions with the Reset method as follows:

```go

// Reset restores all log settings to their default values. func (l *Log) Reset() func Reset()

```

The builtin default logger may be accessed/replaced with:

```go

// Default returns the package's current default logger. func Default() *Log

// SetDefault replaces the package's default logger with the provided one. // It returns the previous default logger. func SetDefault(newDefaultLog *Log) *Log

```

### Logging Levels

Logging functions categorize messages by severity writing to the standard go supplied log package. These functions report plain or formatted diagnostic and status messages:

+-----------+----------------+-----------------------------------------+
| Level     | Functions      | Description                             |
+-----------+----------------+-----------------------------------------+
| Fatal     | F, Fatal       | Plain Critical Errors, program exits    |
|           | Ff, Fatalf     | Formatted Critical Errors, program exits|
| Error     | E, Error       | Plain errors that allow continuation    |
|           | Ef, Errorf     | Formatted errors that allow continuation|
| Warn      | W, Warn        | Plain warnings needing attention        |
|           | Wf, Warnf      | Formatted warnings needing attention    |
| Info      | I, Info        | Plain progress and status info          |
|           | If, Infof      | Formatted progress and status info      |
| Debug     | D, Debug       | Plain developer-focused diagnostics     |
|           | Df, Debugf     | Formatted developer-focused diagnostics |
| Trace     | T, Trace       | Plain detailed program flow             |
|           | Tf, Tracef     | Formatted detailed program flow         |
+-----------+----------------+-----------------------------------------+

### Verbose Output Levels

Verbosity output is completely separate from logging providing 5 levels of plain or formatted messages in addition to normal program output.

The verbose output functions provide fine-grained control over program messaging through six levels: Say0…Say5 and their formatted counterparts Say0f…Say5f. Level 0 represents the default program output, active when no verbosity flags are given or when explicitly set with SetVerbose(0). Increasing levels (1–5) are enabled by supplying additional verbosity flags or calling SetVerbose(1..5), progressively revealing more detailed output. All verbose functions respect the global setting: output is suppressed entirely when --quiet is specified or SetVerbose(-1) is used, ensuring even default level 0 messages are silenced.

+-----------+----------------+-----------------------------------------+
| Level     | Functions      | Typical Use                             |
+-----------+----------------+-----------------------------------------+
| 0         | S0, Say0       | Plain normal program messages           |
|           | S0f, Say0f     | Formatted normal program messages       |
| 1         | S1, Say1       | Plain additional messages               |
|           | S1f, Say1f     | Formatted additional messages           |
| 2         | S2, Say2       | Plain moderate detailed messages        |
|           | S2f, Say2f     | Formatted moderate detailed messages    |
| 3         | S3, Say3       | Plain detailed messages                 |
|           | S3f, Say3f     | Formatted detailed messages             |
| 4         | S4, Say4       | Plain highly detailed messages          |
|           | S4f, Say4f     | Formatted highly detailed messages      |
| 5         | S5, Say5       | Plain maximum verbosity                 |
|           | S5f, Say5f     | Formatted maximum verbosity             |
+-----------+----------------+-----------------------------------------+

## Settings

### Defaults

Settings have defaults which can be overridden by an environment variables.

+-------------+-------------+-------------------------------+
| Area        | Default     | Environment Variable Override |
|-------------|-------------|-------------------------------|
| LongLabels  | false       | SZLOG_LONG_LABELS             |
| LogLevel    | LevelError  | SZLOG_LEVEL                   |
| Language    | ""          | SZLOG_LANGUAGE                |
| Verbose     | 0           | SZLOG_VERBOSE                 |
+-------------+-------------+-------------------------------+

### Command Line Arguments

Settings may also be specified in command line arguments

+-------------+-----------------------------------------------+
| Area        | Argument                                      |
|-------------|-----------------------------------------------|
| LongLabels  | --long-labels                                 |
| LogLevel    | --log <level>                                 |
| Language    | --language <local>                            |
| Verbose     | -v[v...] | --v[v...] | --verbose | --quiet    |
+-------------+-----------------------------------------------+

that are processed with the program functions:

```go

// AbsorbArgs scans the provided argument list for enabled logging-related // flags and updates the log configuration accordingly. Only arguments // specified in the enable set are recognized; all others are ignored. // Recognized flags are removed, and the cleaned argument slice is returned. // Multiple `-v` flags increment verbosity, while invalid or conflicting // combinations (e.g., `-v` with `--quiet`) return an error along with // the original arguments. If no enable set is provided, EnableAll is used. func (l *Log) AbsorbArgs(argsIn []string) ([]string, error) func AbsorbArgs(argsIn []string) ([]string, error)

```

while usage information may be gathered with the program functions:

```go

// ArgUsageInfo reports usage information for all enabled arguments by // invoking the provided callback for each one. Only arguments permitted // in the enable set are included, allowing applications to present // accurate help/usage output tailored to their configuration. func (l *Log) ArgUsageInfo(registerArgs func(string, string)) func ArgUsageInfo(registerArgs func(string, string))

```

### Selective Argument Enabling

The `AbsorbArgs` function accepts an optional set of `EnableArg` constants to restrict which flags are recognized. This allows applications to individually enable or disable handling of built-in arguments. If no constants are provided, `EnableAll` is assumed.

+-----------------------|----------------------|-------------------------+
| Flag / Option         | `EnableArg` constant | Description             |
|-----------------------|----------------------|-------------------------|
| `-v`, `--verbose`     | `EnableVerbose`      | Increase verbosity      |
|                       |                      | (multiple `-v` allowed) |
| `--quiet`             | `EnableQuiet`        | Suppress output         |
| `--log <level>`       | `EnableLogLevel`     | Set log level (all,     |
|                       |                      | trace, debug, info,     |
|                       |                      | warn error, fatal,      |
|                       |                      | none)                   |
| `--language <locale>` | `EnableLanguage`     | Set message language    |
| `--long-labels`       | `EnableLongLabels`   | Use extended labels in  |
|                       |                      | log output              |
| *all of the above*    | `EnableAll`          | Default (recognize all  |
|                       |                      | arguments)              |
+-----------------------|----------------------|-------------------------+

Example usage:

```go

// Only absorb verbosity and quiet flags, ignore all others. args, err := szlog.AbsorbArgs(os.Args, EnableVerbose, EnableQuiet)

```

### When to Disable Arguments

By default, `szlog` absorbs all supported flags. In some applications you may wish to disable certain arguments:

  • **Custom flag parsing**: If your program already defines `--quiet` or `--log`, you can prevent `szlog` from intercepting them by omitting `EnableQuiet` or `EnableLogLevel`.
  • **Minimal CLI surface**: Small utilities may only need `-v` for verbosity and want to skip everything else.
  • **Conflict avoidance**: If another library introduces overlapping flags, selectively enabling arguments avoids collisions.
  • **Explicit control**: Developers who prefer handling configuration programmatically can turn off all arguments and manage `szlog` options directly.

This flexibility ensures that `szlog` integrates smoothly with a variety of command-line setups without forcing a fixed argument model.

### Program Functions

Finally settings man be queried and changed programmatically using library functions.

+-------------+--------------------------------------+
| Area        | Function(s)                          |
|-------------|--------------------------------------|
| Language    | Language()                           |
|             | SetLanguage(language string)         |
| LongLabels  | LongLabels()                         |
|             | SetLongLabels(enable bool)           |
| LogLevel    | Level()                              |
|             | SetLevel(newLogLevel LogLevel)       |
|             | SetCustomLevels(levels ...LogLevel)  |
| Verbose     | Verbose()                            |
|             | SetVerbose(level VerboseLevel)       |
+-------------+--------------------------------------+

implemented as follows:

```go

// Language returns the current language setting used for localized formatting. // An empty string indicates no localization is applied. func (l *Log) Language() string func Language() string

// SetLanguage updates the language used for localized formatting. // Passing an empty string ("") disables localization. It returns any // error encountered while setting the language. func (l *Log) SetLanguage(langStr string) error func SetLanguage(language string) error

// LongLabels reports whether long labels (FATAL, ERROR, WARN, INFO, DEBUG, // TRACE) are currently enabled instead of their short forms (F, E, W, I, D, // T). func (l *Log) LongLabels() bool func LongLabels() bool

// SetLongLabels enables or disables long labels in log output. When disabled, // short labels (F, E, W, I, D, T) are used instead. It returns the previous // setting. func (l *Log) SetLongLabels(enable bool) bool func SetLongLabels(enabled bool) bool

// Level reports the logger's current logging level. func (l *Log) Level() LogLevel func Level() LogLevel

// SetLevel updates the logger's logging level. Valid values include // LevelNone, LevelFatal, LevelError, LevelWarn, LevelInfo, LevelDebug, // LevelTrace, and LevelAll. func (l *Log) SetLevel(newLogLevel LogLevel) LogLevel func SetLevel(newLogLevel LogLevel) LogLevel

// SetCustomLevels enables a custom combination of individual levels. // LevelNone, LevelAll, and LevelCustom are ignored. Internally, this // always results in LevelCustom being applied. func (l *Log) SetCustomLevels(levels ...LogLevel) LogLevel func SetCustomLevels(levels ...LogLevel) LogLevel

// Verbose reports the logger's current verbosity level. func (l *Log) Verbose() VerboseLevel func Verbose() VerboseLevel

// SetVerbose adjusts the verbosity level (-1 through 5). Level -1 silences // all output, while higher levels progressively enable more detail. func (l *Log) SetVerbose(newLevel VerboseLevel) VerboseLevel func SetVerbose(level VerboseLevel) VerboseLevel

```

## Deferred Evaluation

Output function arguments can be wrapped in a func() DEFER, where DEFER is a string type. Deferred functions are only invoked if the target output function is enabled. This avoids the cost of constructing expensive strings or reports that would otherwise be discarded.

This pattern makes it safe to pass in expensive computations without worrying about wasted work if the message is suppressed.

```go

szlog.Info("Report:\n", func() szlog.DEFER {
  return generateReport()
})

```

If Info logging is disabled, generateReport is never executed.

## Localization

Szlog can bind to the Go text package for message localization. SetLanguage accepts a locale string such as "en" or "fr" to select the appropriate translation.

## Convenience Function(s)

```go

// Close is a convenience method for safely closing any io.Closer. If an error // except os.ErrClosed (already closed) occurs during Close, it is logged as a // warning. This method is primarily intended for use in insurance defer // statements. func (l *Log) Close(area string, closeable io.Closer) func Close(area string, closeable io.Closer)

``` ## Use Cases

  • Use logging functions for structured severity-based output.
  • Use verbosity functions for progress and detailed tracing independent of logging configuration.
  • Combine deferred evaluation with either system for maximum performance.

### Quick Start

```go

import "github.com/dancsecs/szlog"

func main() {
  var configFileName string

  args,err:= szlog.AbsorbArgs(os.args,nil) // Set verbose and log level.

  if len(args) != 2 {  // Ignore extra args.
    configFileName = "default.cfg
  } else {
    configFileName = args[1]
  }

  szlog.Info("Application starting\n")

  szlog.Say0f("Processing configuration: %s\n",configFileName)

  szlog.Info("Report:\n", func() szlog.DEFER {
    return longRunningReport()
  })
}

```

NOTE: If Info logging is disabled, longRunningReport() is never executed.

---

## Dedication

This project is dedicated to Reem. Your brilliance, courage, and quiet strength continue to inspire me. Every line is written in gratitude for the light and hope you brought into my life.

---

NOTE: Documentation reviewed and polished with the assistance of ChatGPT from OpenAI.

Index

Constants

View Source
const (
	VerboseFlag     = "[-v | --verbose ...]"
	VerboseFlagDesc = "Increase the verbose level for each v provided."

	QuietFlag     = "[--quiet]"
	QuietFlagDesc = "Sets the verbose level to -1 squashing all " +
		"(non-logged) output."

	LogLevelFlag     = "[--log <level | (levels)>]"
	LogLevelFlagDesc = "Set the level to log (or a custom combination of " +
		"levels).  Valid levels are: " +
		"None, FATAL, ERROR, WARN, INFO, DEBUG,TRACE, ALL."

	LanguageFlag     = "[--language <lang>]"
	LanguageFlagDesc = "Sets the local language used for formatting."

	LongLabelFlag     = "[--long-labels]"
	LongLabelFlagDesc = "Use long labels in log output."
)

Usage suitable strings for verbose argument absorption.

View Source
const (
	EnvLogLevel      = "SZLOG_LEVEL"
	EnvLogLanguage   = "SZLOG_LANGUAGE"
	EnvVerbose       = "SZLOG_VERBOSE"
	EnvLogLongLabels = "SZLOG_LONG_LABELS"
)

Environment variable default overrides.

Variables

View Source
var (
	ErrUnknownLevel             = errors.New("unknown log level")
	ErrInvalidLogLevelParse     = errors.New("invalid log level string")
	ErrAmbiguousVerboseAndQuiet = errors.New("ambiguous verbose and quiet")
	ErrAmbiguousLogLevel        = errors.New("ambiguous log level")
	ErrAmbiguousLanguage        = errors.New("ambiguous language")
	ErrAmbiguousLongLabels      = errors.New("ambiguous long labels")
	ErrMissingLogLevel          = errors.New("missing log level")
	ErrMissingLanguage          = errors.New("missing language")
	ErrInvalidLanguage          = errors.New("invalid language")
)

Exported errors.

Functions

func AbsorbArgs added in v0.0.3

func AbsorbArgs(argsIn []string, enable ...EnableArg) ([]string, error)

AbsorbArgs scans the provided argument list for enabled logging-related flags and updates the log configuration accordingly. Only arguments specified in the enable set are recognized; all others are ignored. Recognized flags are removed, and the cleaned argument slice is returned. Multiple `-v` flags increment verbosity, while invalid or conflicting combinations (e.g., `-v` with `--quiet`) return an error along with the original arguments. If no enable set is provided, EnableAll is used.

func ArgUsageInfo added in v0.0.9

func ArgUsageInfo(registerArgs func(string, string))

ArgUsageInfo reports usage information for all enabled arguments by invoking the provided callback for each one. Only arguments permitted in the enable set are included, allowing applications to present accurate help/usage output tailored to their configuration.

func Close

func Close(area string, closeable io.Closer)

Close is a convenience method for safely closing any io.Closer. If an error occurs during Close, it is logged as a warning. This method is primarily intended for use in defer statements.

func D

func D(msg ...any) bool

D Invokes the default log corresponding method.

func Debug

func Debug(msg ...any) bool

Debug Invokes the default log corresponding method.

func Debugf

func Debugf(msgFmt string, msgArgs ...any) bool

Debugf Invokes the default log corresponding method.

func Df

func Df(msgFmt string, msgArgs ...any) bool

Df Invokes the default log corresponding method.

func E

func E(msg ...any) bool

E Invokes the default log corresponding method.

func Ef

func Ef(msgFmt string, msgArgs ...any) bool

Ef Invokes the default log corresponding method.

func Error

func Error(msg ...any) bool

Error Invokes the default log corresponding method.

func Errorf

func Errorf(msgFmt string, msgArgs ...any) bool

Errorf Invokes the default log corresponding method.

func F

func F(msg ...any) bool

F Invokes the default log corresponding method.

func Fatal

func Fatal(msg ...any) bool

Fatal Invokes the default log corresponding method.

func Fatalf

func Fatalf(msgFmt string, msgArgs ...any) bool

Fatalf Invokes the default log corresponding method.

func Ff

func Ff(msgFmt string, msgArgs ...any) bool

Ff Invokes the default log corresponding method.

func I

func I(msg ...any) bool

I Invokes the default log corresponding method.

func If

func If(msgFmt string, msgArgs ...any) bool

If Invokes the default log corresponding method.

func Info

func Info(msg ...any) bool

Info Invokes the default log corresponding method.

func Infof

func Infof(msgFmt string, msgArgs ...any) bool

Infof Invokes the default log corresponding method.

func Language added in v0.0.3

func Language() string

Language returns the current language setting used for localized formatting. An empty string indicates no localization is applied.

func LogDebug added in v0.0.3

func LogDebug() bool

LogDebug returns true if debug messages are being logged.

func LogError added in v0.0.3

func LogError() bool

LogError returns true if error messages are being logged.

func LogFatal added in v0.0.3

func LogFatal() bool

LogFatal returns true if fatal messages are being logged.

func LogInfo added in v0.0.3

func LogInfo() bool

LogInfo returns true if information messages are being logged.

func LogTrace added in v0.0.3

func LogTrace() bool

LogTrace returns true if tracing messages are being logged.

func LogWarn added in v0.0.3

func LogWarn() bool

LogWarn returns true if warning messages are being logged.

func LongLabels

func LongLabels() bool

LongLabels reports whether long labels (FATAL, ERROR, WARN, INFO, DEBUG, TRACE) are currently enabled instead of their short forms (F, E, W, I, D, T).

func Reset

func Reset()

Reset restores all log settings to their default values.

func S0 added in v0.0.3

func S0(msg ...any) bool

S0 Invokes the default verbose corresponding method.

func S0f added in v0.0.3

func S0f(msgFmt string, msgArgs ...any) bool

S0f Invokes the default verbose corresponding method.

func S1 added in v0.0.3

func S1(msg ...any) bool

S1 Invokes the default verbose corresponding method.

func S1f added in v0.0.3

func S1f(msgFmt string, msgArgs ...any) bool

S1f Invokes the default verbose corresponding method.

func S2 added in v0.0.3

func S2(msg ...any) bool

S2 Invokes the default verbose corresponding method.

func S2f added in v0.0.3

func S2f(msgFmt string, msgArgs ...any) bool

S2f Invokes the default verbose corresponding method.

func S3 added in v0.0.3

func S3(msg ...any) bool

S3 Invokes the default verbose corresponding method.

func S3f added in v0.0.3

func S3f(msgFmt string, msgArgs ...any) bool

S3f Invokes the default verbose corresponding method.

func S4 added in v0.0.3

func S4(msg ...any) bool

S4 Invokes the default verbose corresponding method.

func S4f added in v0.0.3

func S4f(msgFmt string, msgArgs ...any) bool

S4f Invokes the default verbose corresponding method.

func S5 added in v0.0.3

func S5(msg ...any) bool

S5 Invokes the default verbose corresponding method.

func S5f added in v0.0.3

func S5f(msgFmt string, msgArgs ...any) bool

S5f Invokes the default verbose corresponding method.

func Say0 added in v0.0.3

func Say0(msg ...any) bool

Say0 Invokes the default verbose corresponding method.

func Say0f added in v0.0.3

func Say0f(msgFmt string, msgArgs ...any) bool

Say0f Invokes the default verbose corresponding method.

func Say1 added in v0.0.3

func Say1(msg ...any) bool

Say1 Invokes the default verbose corresponding method.

func Say1f added in v0.0.3

func Say1f(msgFmt string, msgArgs ...any) bool

Say1f Invokes the default verbose corresponding method.

func Say2 added in v0.0.3

func Say2(msg ...any) bool

Say2 Invokes the default verbose corresponding method.

func Say2f added in v0.0.3

func Say2f(msgFmt string, msgArgs ...any) bool

Say2f Invokes the default verbose corresponding method.

func Say3 added in v0.0.3

func Say3(msg ...any) bool

Say3 Invokes the default verbose corresponding method.

func Say3f added in v0.0.3

func Say3f(msgFmt string, msgArgs ...any) bool

Say3f Invokes the default verbose corresponding method.

func Say4 added in v0.0.3

func Say4(msg ...any) bool

Say4 Invokes the default verbose corresponding method.

func Say4f added in v0.0.3

func Say4f(msgFmt string, msgArgs ...any) bool

Say4f Invokes the default verbose corresponding method.

func Say5 added in v0.0.3

func Say5(msg ...any) bool

Say5 Invokes the default verbose corresponding method.

func Say5f added in v0.0.3

func Say5f(msgFmt string, msgArgs ...any) bool

Say5f Invokes the default verbose corresponding method.

func SetLanguage added in v0.0.3

func SetLanguage(language string) error

SetLanguage updates the language used for localized formatting. Passing an empty string ("") disables localization. It returns any error encountered while setting the language.

func SetLongLabels

func SetLongLabels(enabled bool) bool

SetLongLabels enables or disables long labels in log output. When disabled, short labels (F, E, W, I, D, T) are used instead. It returns the previous setting.

func T

func T(msg ...any) bool

T Invokes the default log corresponding method.

func Tf

func Tf(msgFmt string, msgArgs ...any) bool

Tf Invokes the default log corresponding method.

func Trace

func Trace(msg ...any) bool

Trace Invokes the default log corresponding method.

func Tracef

func Tracef(msgFmt string, msgArgs ...any) bool

Tracef Invokes the default log corresponding method.

func W

func W(msg ...any) bool

W Invokes the default log corresponding method.

func Warn

func Warn(msg ...any) bool

Warn Invokes the default log corresponding method.

func Warnf

func Warnf(msgFmt string, msgArgs ...any) bool

Warnf Invokes the default log corresponding method.

func Wf

func Wf(msgFmt string, msgArgs ...any) bool

Wf Invokes the default log corresponding method.

Types

type Defer

type Defer string

Defer marks a function argument for deferred evaluation. The function is only executed and its result logged if the current log level permits; otherwise, it is skipped entirely.

type EnableArg added in v0.0.14

type EnableArg int

EnableArg specifies which command-line arguments szlog should recognize and process. These values can be combined and passed to AbsorbArgs to restrict handling to a subset of arguments. If no values are provided, EnableAll is assumed by default.

const (
	EnableVerbose EnableArg = 1 << iota
	EnableQuiet
	EnableLogLevel
	EnableLanguage
	EnableLongLabels

	EnableAll EnableArg = math.MaxInt
)

EnableArg flags define which arguments are recognized by AbsorbArgs and ArgUsageInfo. Multiple values can be provided (or combined with a bitwise OR.)

EnableVerbose    - enable verbosity flags (-v, --verbose)
EnableQuiet      - enable quiet flag (--quiet)
EnableLogLevel   - enable log level flag (--log <level>)
EnableLanguage   - enable language/locale flag (--language <locale>)
EnableLongLabels - enable long-labels flag (--long-labels)
EnableAll        - enable all supported argument flags

type Log

type Log struct {
	LogFatal bool
	LogError bool
	LogWarn  bool
	LogInfo  bool
	LogDebug bool
	LogTrace bool

	// Logging functions
	F, Fatal   LogFunc
	Ff, Fatalf LogFuncf
	E, Error   LogFunc
	Ef, Errorf LogFuncf
	W, Warn    LogFunc
	Wf, Warnf  LogFuncf
	I, Info    LogFunc
	If, Infof  LogFuncf
	D, Debug   LogFunc
	Df, Debugf LogFuncf
	T, Trace   LogFunc
	Tf, Tracef LogFuncf

	// Verbose functions
	S0, Say0   LogFunc
	S0f, Say0f LogFuncf
	S1, Say1   LogFunc
	S1f, Say1f LogFuncf
	S2, Say2   LogFunc
	S2f, Say2f LogFuncf
	S3, Say3   LogFunc
	S3f, Say3f LogFuncf
	S4, Say4   LogFunc
	S4f, Say4f LogFuncf
	S5, Say5   LogFunc
	S5f, Say5f LogFuncf
	// contains filtered or unexported fields
}

Log represents a szlog logging object.

func Default

func Default() *Log

Default returns the package's current default logger.

func New

func New() *Log

New returns a new Log instance with default settings.

func SetDefault

func SetDefault(newDefaultLog *Log) *Log

SetDefault replaces the package's default logger with the provided one. It returns the previous default logger.

func (*Log) AbsorbArgs added in v0.0.3

func (l *Log) AbsorbArgs(
	argsIn []string, enable ...EnableArg,
) ([]string, error)

AbsorbArgs scans the provided argument list for enabled logging-related flags and updates the log configuration accordingly. Only arguments specified in the enable set are recognized; all others are ignored. Recognized flags are removed, and the cleaned argument slice is returned. Multiple `-v` flags increment verbosity, while invalid or conflicting combinations (e.g., `-v` with `--quiet`) return an error along with the original arguments. If no enable set is provided, EnableAll is used.

func (*Log) ArgUsageInfo added in v0.0.9

func (l *Log) ArgUsageInfo(registerArg func(string, string))

ArgUsageInfo reports usage information for all enabled arguments by invoking the provided callback for each one. Only arguments permitted in the enable set are included, allowing applications to present accurate help/usage output tailored to their configuration.

func (*Log) Close

func (l *Log) Close(area string, closeable io.Closer)

Close is a convenience method for safely closing any io.Closer. If an error except os.ErrClosed (already closed) occurs during Close, it is logged as a warning. This method is primarily intended for use in insurance defer statements.

func (*Log) Language added in v0.0.3

func (l *Log) Language() string

Language returns the current language setting used for localized formatting. An empty string indicates no localization is applied.

func (*Log) Level

func (l *Log) Level() LogLevel

Level reports the logger's current logging level.

func (*Log) LongLabels

func (l *Log) LongLabels() bool

LongLabels reports whether long labels (FATAL, ERROR, WARN, INFO, DEBUG, TRACE) are currently enabled instead of their short forms (F, E, W, I, D, T).

func (*Log) Reset

func (l *Log) Reset()

Reset restores all log settings to their default values.

func (*Log) SetCustomLevels

func (l *Log) SetCustomLevels(levels ...LogLevel) LogLevel

SetCustomLevels enables a custom combination of individual levels. LevelNone, LevelAll, and LevelCustom are ignored. Internally, this always results in LevelCustom being applied.

func (*Log) SetLanguage added in v0.0.3

func (l *Log) SetLanguage(langStr string) error

SetLanguage updates the language used for localized formatting. Passing an empty string ("") disables localization. It returns any error encountered while setting the language.

func (*Log) SetLevel

func (l *Log) SetLevel(newLogLevel LogLevel) LogLevel

SetLevel updates the logger's logging level. Valid values include LevelNone, LevelFatal, LevelError, LevelWarn, LevelInfo, LevelDebug, LevelTrace, and LevelAll.

func (*Log) SetLongLabels

func (l *Log) SetLongLabels(enable bool) bool

SetLongLabels enables or disables long labels in log output. When disabled, short labels (F, E, W, I, D, T) are used instead. It returns the previous setting.

func (*Log) SetVerbose added in v0.0.3

func (l *Log) SetVerbose(newLevel VerboseLevel) VerboseLevel

SetVerbose adjusts the verbosity level (-1 through 5). Level -1 silences all output, while higher levels progressively enable more detail.

func (*Log) Verbose added in v0.0.3

func (l *Log) Verbose() VerboseLevel

Verbose reports the logger's current verbosity level.

type LogFunc

type LogFunc func(msg ...any) bool

LogFunc defines the signature of an unformatted log function.

type LogFuncf

type LogFuncf func(msgFmt string, msgArgs ...any) bool

LogFuncf defines the signature of a formatted log function.

type LogLevel

type LogLevel int

LogLevel defines the minimum severity of messages that will be logged.

const (
	LevelNone LogLevel = iota
	LevelFatal
	LevelError
	LevelWarn
	LevelInfo
	LevelDebug
	LevelTrace
	LevelAll
	LevelCustom = LogLevel(math.MaxInt)
)

Standard log levels in order of increasing verbosity. LevelCustom is a special case used internally to represent user-defined combinations.

func Level

func Level() LogLevel

Level reports the logger's current logging level.

func LogLevelFromString added in v0.0.3

func LogLevelFromString(raw string) (LogLevel, error)

LogLevelFromString parses a string into a LogLevel. Recognized values include: none, fatal, error, warn, info, debug, trace, all, and custom. Matching is case-insensitive.

func SetCustomLevels

func SetCustomLevels(levels ...LogLevel) LogLevel

SetCustomLevels enables a custom combination of individual levels. LevelNone, LevelAll, and LevelCustom are ignored. Internally, this always results in LevelCustom being applied.

func SetLevel

func SetLevel(newLogLevel LogLevel) LogLevel

SetLevel updates the logger's logging level. Valid values include LevelNone, LevelFatal, LevelError, LevelWarn, LevelInfo, LevelDebug, LevelTrace, and LevelAll.

func (LogLevel) String

func (ll LogLevel) String() string

String implements the Stringer interface.

type VerboseLevel added in v0.0.3

type VerboseLevel = int

VerboseLevel indicates how much non-essential output is allowed. Levels range from -1 (silent) to 5 (most verbose).

func SetVerbose added in v0.0.3

func SetVerbose(level VerboseLevel) VerboseLevel

SetVerbose adjusts the verbosity level (-1 through 5). Level -1 silences all output, while higher levels progressively enable more detail.

func Verbose added in v0.0.3

func Verbose() VerboseLevel

Verbose reports the logger's current verbosity level.

Jump to

Keyboard shortcuts

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