printer

package module
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2025 License: GPL-3.0 Imports: 12 Imported by: 0

README

Printer Package

The printer package provides a comprehensive logging utility with color formatting for console output. It allows for various log levels and formatted output to standard output and error streams.

Features

  • Log messages with different levels: Error, Warn, Info, Debug.
  • Color formatting for log messages.
  • Thread-safe logging.
  • Global printer instance for easy logging.
  • Structured logging with fields.
  • Log truncation for long messages.
  • Field truncation for long fields.

Installation

To install the printer package, use go get:

go get github.com/cruffinoni/printer

Usage

Creating a Printer

To create a new Printer instance, use the NewPrint function:

import (
    "os"
    "github.com/cruffinoni/printer"
)

printer := printer.NewPrint(printer.LevelDebug, printer.FlagWithDate|printer.FlagWithGoroutineID, os.Stdin, os.Stdout, os.Stderr)
Logging Methods
Global Printer Functions

The package provides a global printer instance for convenience:

printer.Printf("Hello, %s!", "world")
printer.Print("This is a standard message.")
printer.PrintError(fmt.Errorf("This is an error message."))
printer.Errorf("This is a formatted error message: %s", "error details")
printer.Warnf("This is a warning message.")
printer.Infof("This is an info message.")
printer.Debugf("This is a debug message.")
Printer Methods

For more control, you can use the Printer methods:

printer.WriteToStd([]byte("Standard message"))
printer.WriteToError([]byte("Error message"))
printer.Errorf("Formatted error message: %s", "error details")
printer.Warnf("Warning message")
printer.Infof("Info message")
printer.Debugf("Debug message")
Structured Logging

The Printer struct supports structured logging with fields. You can add fields to log entries using the WithField and WithFields methods.

Adding a Single Field

To add a single field to a log entry, use the WithField method:

printer.WithField("key", "value").Infof("This is an info message with a field")
Adding Multiple Fields

To add multiple fields to a log entry, use the WithFields method:

fields := printer.LogFields{
    "key1": "value1",
    "key2": "value2",
}
printer.WithFields(fields).Infof("This is an info message with multiple fields")
Printing Out Fields

When there are fields added to a log entry, the Printer struct will print out the fields in the log message. The fields will be included in the log prefix.

Example:

fields := printer.LogFields{
    "user": "john_doe",
    "action": "login",
}
printer.WithFields(fields).Infof("User action logged")

The log message will include the fields in the prefix:

[15:04:05.000 | INFO | user=john_doe, action=login] User action logged
Setting and Getting Log Level

To set the log level:

printer.SetLogLevel(printer.LevelInfo)

To get the current log level:

logLevel := printer.GetLogLevel()
fmt.Println("Current log level:", logLevel)
Setting Maximum Log Length

To set the maximum log length for truncation:

printer.SetMaxLogLength(100)
Setting Maximum Field Length

To set the maximum field length for truncation:

printer.SetMaxFieldLength(50)
Closing the Printer

To close the Printer and its associated files:

err := printer.Close()
if err != nil {
    fmt.Println("Error closing printer:", err)
}
Flags

The Printer struct includes flags to control the logging behavior. The available flags are:

  • FlagWithDate: Include the current date and time in log messages.
  • FlagWithGoroutineID: Include the goroutine ID in log messages.
  • FlagWithColor: Enable color formatting in log messages (enabled by default).
  • FlagTruncateLogs: Enable log truncation.
  • FlagTruncateFields: Enable field truncation.

To create a new Printer instance with specific flags, use the NewPrint function and combine the flags using the bitwise OR operator (|):

printer := printer.NewPrint(printer.LevelDebug, printer.FlagWithDate|printer.FlagWithGoroutineID, os.Stdout, os.Stderr)

Log Levels

The package defines four log levels:

  • LevelError (0)
  • LevelWarn (1)
  • LevelInfo (2)
  • LevelDebug (3)

Color Formatting

The package supports color formatting using special tags:

  • Foreground Colors: F_<color>
  • Background Colors: B_<color>
  • Options: BOLD, FAINT, UNDERLINED, SLOWBLINK, RESET
  • Colors: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE

Example:

printer.Print("{{{-F_RED,BOLD}}}This is a bold red message{{{-RESET}}}")

Contributing

Contributions are welcome! Please fork the repository and submit a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	Reset = iota
	Bold
	Faint
	Underlined = 4
	SlowBlink  = 5
)
View Source
const (
	ForegroundBlack = iota + 30
	ForegroundRed
	ForegroundGreen
	ForegroundYellow
	ForegroundBlue
	ForegroundMagenta
	ForegroundCyan
	ForegroundWhite
)
View Source
const (
	BackgroundBlack = iota + 40
	BackgroundRed
	BackgroundGreen
	BackgroundYellow
	BackgroundBlue
	BackgroundMagenta
	BackgroundCyan
	BackgroundWhite
)
View Source
const (
	DefaultMaxLogLength   = 100
	DefaultMaxFieldLength = 50
)

Default values for log and field truncation

Variables

This section is empty.

Functions

func Debugf

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

Debugf logs a formatted debug message using the global printer.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func Errorf

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

Errorf logs a formatted error message using the global printer.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func Infof

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

Infof logs a formatted informational message using the global printer.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func Print

func Print(s string)

Print writes a plain string to the standard output stream using the global printer.

Parameters:

  • s: string - The message to write.

func PrintError

func PrintError(err error)

PrintError writes an error message to the error output stream using the global printer.

Parameters:

  • err: error - The error to write. If nil, "<nil>" is printed.

func PrintErrorS

func PrintErrorS(err string)

PrintErrorS writes a plain error string to the error output stream using the global printer.

Parameters:

  • err: string - The error message to write.

func PrintErrorSf

func PrintErrorSf(err string, args ...any)

PrintErrorSf formats and writes an error message to the error output stream using the global printer.

Parameters:

  • err: string - The format string.
  • args: ...any - The arguments to format.

func Printf

func Printf(p string, a ...any)

Printf formats and writes a message to the standard output stream using the global printer.

Parameters:

  • p: string - The format string.
  • a: ...any - The arguments to format.

func SetLogLevel

func SetLogLevel(level Levels)

SetLogLevel updates the global printer's log level.

Parameters:

  • level: int - The new log level to set.

func Warnf

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

Warnf logs a formatted warning message using the global printer.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

Types

type Flags

type Flags uint

Flags represents a set of configurable options for the Printer.

This type is defined as an unsigned integer and uses bitwise operations to enable multiple flags to be combined and checked efficiently.

const (
	// WithNoFlags is the default value for Flags, indicating no special options are set.
	WithNoFlags Flags = 0

	// FlagWithDate enables the inclusion of the current date in the output.
	FlagWithDate Flags = 1 << iota

	// FlagWithGoroutineID enables the inclusion of the current goroutine ID in the output.
	FlagWithGoroutineID

	// FlagWithColor enables colored output for better readability.
	FlagWithColor

	// FlagPanicOnError enables panic behavior on error conditions.
	FlagPanicOnError

	// FlagWithoutNewLine disables the automatic newline at the end of the output.
	FlagWithoutNewLine

	// FlagTruncateLogs enables truncation of log messages to a specified length.
	FlagTruncateLogs

	// FlagTruncateFields enables truncation of field values to a specified length.
	FlagTruncateFields
)

type Levels

type Levels int
const (
	LevelError Levels = iota // Error level logging
	LevelWarn                // Warning level logging
	LevelInfo                // Info level logging
	LevelDebug               // Debug level logging
)

func GetLogLevel

func GetLogLevel() Levels

GetLogLevel retrieves the current log level of the global printer.

Returns:

  • int: The current global log level.

func (Levels) GetColor added in v2.4.0

func (l Levels) GetColor() string

GetColor returns the color code for the given logging level.

func (Levels) String added in v2.4.0

func (l Levels) String() string

String returns the string representation of the logging level.

type LogFields

type LogFields map[string]any

LogFields represents a map of log fields for structured logging.

type Printer

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

Printer provides structured output to various I/O streams with support for log levels, colored output, and concurrency-safe operations.

func NewPrinter added in v2.4.0

func NewPrinter(loglevel Levels, flags Flags, out, err io.WriteCloser) *Printer

NewPrinter creates a new Printer instance with specified log level and I/O streams.

Parameters:

  • loglevel: int - The initial logging level.
  • out: io.WriteCloser - The output stream for standard messages.
  • err: io.WriteCloser - The output stream for error messages.

Returns:

  • *Printer: A new Printer instance.

func WithField

func WithField(key string, value any) *Printer

WithField adds a single key-value pair to the global printer's context.

Parameters:

  • key: string - The key for the field.
  • value: any - The value associated with the key.

Returns:

  • *Printer: A new Printer instance with the added field.

func WithFields

func WithFields(fields LogFields) *Printer

WithFields adds multiple key-value pairs to the global printer's context.

Parameters:

  • fields: LogFields - A map containing the fields to add.

Returns:

  • *Printer: A new Printer instance with the added fields.

func WithoutColor added in v2.4.0

func WithoutColor() *Printer

WithoutColor returns a new Printer instance that disables colored output.

Returns:

  • *Printer: A new Printer instance with color disabled.

func WithoutNewLine added in v2.4.0

func WithoutNewLine() *Printer

WithoutNewLine returns a new Printer instance that disables appending a newline character at the end of the output.

Returns:

  • *Printer: A new Printer instance with newline suppression.

func (*Printer) Close

func (p *Printer) Close() error

Close safely closes all associated I/O streams of the Printer.

This method iterates over all associated I/O streams (`out` and `err`) and attempts to close them. If any stream fails to close, the method returns the encountered error. If all streams are closed successfully, it returns nil.

Returns:

  • error: An error encountered during the close operation, or nil if all streams are closed successfully.

func (*Printer) Copy added in v2.2.0

func (p *Printer) Copy() *Printer

Copy creates a new Printer instance with the same configuration as the current one.

Returns:

  • *Printer: A new Printer instance with the same configuration.

func (*Printer) Debugf

func (p *Printer) Debugf(format string, a ...any)

Debugf logs a debug message if the log level permits.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func (*Printer) Errorf

func (p *Printer) Errorf(format string, a ...any)

Errorf logs an error message if the log level permits.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func (*Printer) GetLogLevel

func (p *Printer) GetLogLevel() Levels

GetLogLevel retrieves the current log level.

Returns:

  • int: The current log level.

func (*Printer) Infof

func (p *Printer) Infof(format string, a ...any)

Infof logs an informational message if the log level permits.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func (*Printer) Print added in v2.3.0

func (p *Printer) Print(s string)

Print writes a raw string to the standard output stream.

Parameters:

  • s: string - The string to write.

func (*Printer) Printf added in v2.3.0

func (p *Printer) Printf(format string, a ...any)

Printf writes a formatted string to the standard output stream.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func (*Printer) SetLogLevel

func (p *Printer) SetLogLevel(level Levels)

SetLogLevel updates the log level of the Printer.

Parameters:

  • level: int - The new log level to set.

func (*Printer) SetMaxFieldLength added in v2.6.0

func (p *Printer) SetMaxFieldLength(length int)

SetMaxFieldLength sets the maximum field length for truncation.

Parameters:

  • length: int - The maximum field length to set.

func (*Printer) SetMaxLogLength added in v2.6.0

func (p *Printer) SetMaxLogLength(length int)

SetMaxLogLength sets the maximum log length for truncation.

Parameters:

  • length: int - The maximum log length to set.

func (*Printer) Warnf

func (p *Printer) Warnf(format string, a ...any)

Warnf logs a warning message if the log level permits.

Parameters:

  • format: string - The format string.
  • a: ...any - The arguments to format.

func (*Printer) WithField

func (p *Printer) WithField(key string, value any) *Printer

WithField creates a new Printer instance with an additional single field.

This method performs a deep copy of the current Printer instance and adds the specified key-value pair to the fields map of the new instance.

Parameters:

  • key: string - The key for the new field.
  • value: any - The value for the new field.

Returns:

  • *Printer: A new Printer instance with the added field.

func (*Printer) WithFields

func (p *Printer) WithFields(fields LogFields) *Printer

WithFields creates a new Printer instance with additional fields.

This method performs a deep copy of the current Printer instance and adds the specified key-value pairs to the fields map of the new instance.

Parameters:

  • fields: LogFields - A map of key-value pairs to add to the fields.

Returns:

  • *Printer: A new Printer instance with the added fields.

func (*Printer) WithoutColor added in v2.4.0

func (p *Printer) WithoutColor() *Printer

WithoutColor creates a new Printer instance with color output disabled.

Returns:

  • *Printer: A new Printer instance with the color flag disabled.

func (*Printer) WithoutNewLine added in v2.4.0

func (p *Printer) WithoutNewLine() *Printer

WithoutNewLine creates a new Printer instance with the newline flag disabled.

This method performs a deep copy of the current Printer instance and sets the WithoutNewLine flag in the new instance.

Returns:

  • *Printer: A new Printer instance with the WithoutNewLine flag set.

func (*Printer) Write

func (p *Printer) Write(buffer []byte) (n int, err error)

Write writes a byte slice to the standard output stream.

Parameters:

  • buffer: []byte - The data to write.

Returns:

  • int: Number of bytes written.
  • error: Error encountered during write.

func (*Printer) WriteToErr

func (p *Printer) WriteToErr(b []byte)

WriteToErr writes a raw message to the error output stream.

Parameters:

  • b: []byte - The message to write.

func (*Printer) WriteToStd

func (p *Printer) WriteToStd(b []byte)

WriteToStd writes a raw message to the standard output stream.

Parameters:

  • b: []byte - The message to write.

Jump to

Keyboard shortcuts

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