loggo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2024 License: MIT Imports: 9 Imported by: 0

README

Loggo - A Go Logging Library

Go Reference License Go Report Card codecov

CI CodeQL Dependabot Updates

 __         ______     ______     ______     ______    
/\ \       /\  __ \   /\  ___\   /\  ___\   /\  __ \   
\ \ \____  \ \ \/\ \  \ \ \__ \  \ \ \__ \  \ \ \/\ \  
 \ \_____\  \ \_____\  \ \_____\  \ \_____\  \ \_____\ 
  \/_____/   \/_____/   \/_____/   \/_____/   \/_____/ 
                                                       

Loggo is a simple and flexible logging library for Go, offering configurable log levels, output destinations, message templates, time providers, and more.

Note: This library has no external dependencies.

Table of Contents

Features

  • Configurable log levels (Debug, Info, Warn, Error, Fatal)
  • Customizable output destinations (e.g., os.Stdout, os.Stderr, files)
  • Flexible message templates
  • Custom time providers for log timestamps
  • Custom time formats for log timestamps
  • Configurable maximum log message size
  • Thread-safe logging

Installation

To install Loggo, run:

go get github.com/hvpaiva/loggo

Usage

Basic Usage

Initialize a logger with a specified log level and log messages:

package main

import "github.com/hvpaiva/loggo"

func main() {
    logger := loggo.New(loggo.LevelInfo)
	
    logger.Info("This is an info message")
    logger.Debug("This debug message will not be logged")
    // Output: 2024-09-03 15:04:05 [ INFO]: This is an info message
}
Custom Output

Redirect logs to a file instead of standard output:

package main

import (
    "os"


    "github.com/hvpaiva/loggo"
)

func main() {
    file, _ := os.Create("log.txt")
    logger := loggo.New(loggo.LevelInfo, loggo.WithOutput(file))
	
    logger.Info("This message will be logged to a file")
	// In the file log.txt:
	// Output: 2024-09-03 15:04:05 [ INFO]: This message will be logged to a file
}
Custom Template

Define a custom format for log messages:

package main

import "github.com/hvpaiva/loggo"

func main() {
    logger := loggo.New(loggo.LevelInfo, loggo.WithTemplate("{{.Time}} - {{.Message}}"))
    logger.Info("This is an info message")
    // Output: 2024-09-03 15:04:05 - This is an info message
}

Available template placeholders:

  • {{.Level}}: log level (e.g., "INFO", "DEBUG")
  • {{.Time}}: log timestamp (e.g., "2024-09-03 15:04:05")
  • {{.Message}}: log message
  • {{.Caller}}: log caller (e.g., "main.go:10")

Default template: {{.Time}} [{{printf \"%5s\" .Level}}]: {{.Message}}.

Custom Time Provider

Specify a custom time provider for timestamps:

package main

import (
    "time"


    "github.com/hvpaiva/loggo"
)

func fakeNow() time.Time {
    return time.Unix(0, 0)
}

func main() {
    logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow))
    logger.Info("This message will have a custom timestamp")
    // Output: 1970-01-01 00:00:00 [ INFO]: This message will have a custom timestamp
}
Custom Time Format

Set a custom time format for timestamps:

package main

import "github.com/hvpaiva/loggo"

func main() {
	logger := loggo.New(
		loggo.LevelInfo,
		loggo.WithTimeFormat("02/01/2006 15:04:05"),
	)
    logger.Info("This message will have a custom time format")
    // Output: 01/02/2006 15:04:05 [ INFO]: This message will have a custom time format
}
Maximum Log Message Size

Limit the maximum size of a log message:

package main

import "github.com/hvpaiva/loggo"

func main() {
	logger := loggo.New(
		loggo.LevelInfo,
		loggo.WithMaxSize(10),
	)
    logger.Info("This is an info message with a maximum size")
    // Output: 2024-09-03 15:04:05 [ INFO]: This is an
}
Custom Caller Provider

Use a custom caller provider for log caller information:

package main

import "github.com/hvpaiva/loggo"

func main() {
    logger := loggo.New(
        loggo.LevelInfo,
        loggo.WithCallerProvider(func() (pc uintptr, file string, line int, ok bool) {
            return 0, "custom caller", 0, true
        }),
		loggo.WithTemplate("{{.Caller}} - {{.Message}}"),
    )
    logger.Info("This is an info message with a custom caller")
    // Output: custom caller:0 - This is an info message with a custom caller
}
Context Logging

Enhance a logger with additional context using WithContext:

package main

import (
    "context"

    "github.com/hvpaiva/loggo"
)

func main() {
    ctx := context.WithValue(context.Background(), "trace_id", "123456")

    logger := loggo.New(loggo.LevelInfo, loggo.WithContext(ctx))
    logger.Infof("This is an info message with context, trace_id: %s", logger.Context.Value("trace_id"))
    // Output: 2024-09-03 15:04:05 [ INFO]: This is an info message with context, trace_id: 123456
}
Pre & Post Log Hooks

Execute custom logic before and after a log message:

package main

import (
    "fmt"
    "strings"

    "github.com/hvpaiva/loggo"
)

func main() {
    logger := loggo.New(
        loggo.LevelInfo,
        loggo.WithPreHook(func(l *loggo.Logger, msg *string) {
            *msg = strings.ToUpper(*msg)
        }),
        loggo.WithPostHook(func(l *loggo.Logger, msg *string) {
            fmt.Println("Log message written:", *msg)
        }),
    )

    logger.Info("This is an info message")
    // Output: 2024-09-03 15:04:05 [ INFO]: THIS IS AN INFO MESSAGE
    // Log message written: THIS IS AN INFO MESSAGE
}

Thread-Safe Logging

Loggo ensures thread safety using a mutex:

package main

import (
  "os"
  "sync"

  "github.com/hvpaiva/loggo"
)

func main() {
  logger := loggo.New(loggo.LevelInfo, loggo.WithOutput(os.Stdout))
  var wg sync.WaitGroup

  for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(i int) {
      defer wg.Done()
      logger.Infof("Logging from goroutine %d", i)
    }(i)
  }

  wg.Wait()
}

Comparison with Go's Standard Library

Loggo provides several advantages over the Go standard library log package:

Feature Loggo Go Log
Configurable log levels Yes No*
Customizable output destinations Yes Yes
Flexible message templates Yes No**
Formatted log messages Yes Yes
Custom time providers Yes No
Custom time formats Yes No
Maximum log message size Yes No
Thread-safe logging Yes Yes
Custom caller provider Yes No***

* Go's log level is action-based with functions like log.Print, log.Fatal, and log.Panic.

** Predefined message format in Go's log.

*** Caller info in Go's log is not configurable.

Documentation

For detailed documentation and examples, visit the GoDoc.

Contributing

Contributions are welcome! Feel free to open an issue or submit a pull request on GitHub.

License

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

Documentation

Overview

Package loggo provides a simple logging library with configurable log levels, output destinations, and message templates.

The loggo package allows you to create a Logger with a specified log level Threshold and various options to customize its behavior. You can log messages at different levels such as Debug, Info, Warn, Error, and Fatal.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CallerProvider

type CallerProvider func() (pc uintptr, file string, line int, ok bool)

CallerProvider is a function that returns the path of the caller, the file name, and the line number, and a boolean indicating if the information is available.

type Hook added in v1.0.0

type Hook func(l *Logger, message *string)

Hook is a function that is executed before or after logging a message.

type Level

type Level byte

Level represents an available log level.

The log levels are ordered by severity, with LevelDebug being the lowest and LevelFatal being the highest. The levels are: - LevelDebug: Used for debugging purposes. - LevelInfo: Used to log general information about the application. - LevelWarn: Used to log warnings about potential issues. - LevelError: Used to log errors that do not cause the application to stop. - LevelFatal: Used to log fatal errors that cause the application to stop.

const (
	// LevelDebug is the lowest level and is mostly used for debugging purposes.
	LevelDebug Level = iota
	// LevelInfo is used to log general information about the application.
	LevelInfo
	// LevelWarn is used to log warnings about potential issues.
	LevelWarn
	// LevelError is used to log errors that do not cause the application to stop.
	LevelError
	// LevelFatal is used to log fatal errors that cause the application to stop.
	LevelFatal
)

Available log levels.

func (Level) String

func (l Level) String() string

String returns the string representation of the log level.

type Logger

type Logger struct {
	Context   context.Context // Context for the logger
	Threshold Level           // Minimum log level to output
	// contains filtered or unexported fields
}

Logger is the structure that holds the logger information. It includes the log level Threshold, output destination, message template, and time provider.

func New

func New(threshold Level, options ...Option) *Logger

New creates a new Logger with the given Threshold and options. The default output is os.Stdout, the default template is "%s [%5s]: %s", and the default time provider is time.Now.

Parameters:

  • Threshold: Minimum log level to output.
  • options: Variadic options to configure the Logger.

Returns:

  • A pointer to the newly created Logger.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithOutput(os.Stderr))
logger.Info("This is an info message")

func (*Logger) Debug

func (l *Logger) Debug(message string)

Debug logs a message at the LevelDebug. If an error occurs while logging the message, it is ignored.

Parameters:

  • message: The debug message to log.

Example:

logger := loggo.New(loggo.LevelDebug)
logger.Debug("This is a debug message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelDebug, loggo.WithTimeProvider(fakeNow))
	logger.Debug("This is a debug log message")
}
Output:
2022-01-25 00:00:00 [DEBUG]: This is a debug log message

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...any)

Debugf logs a formatted message at the LevelDebug. If an error occurs while logging the message, it is ignored.

Parameters:

  • format: The format string for the debug message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelDebug)
logger.Debugf("This is a debug message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelDebug, loggo.WithTimeProvider(fakeNow))
	logger.Debugf("This is a debug log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [DEBUG]: This is a debug log message with a "format"

func (*Logger) Error

func (l *Logger) Error(message string)

Error logs a message at the LevelError. If an error occurs while logging the message, it is ignored.

Parameters:

  • message: The error message to log.

Example:

logger := loggo.New(loggo.LevelError)
logger.Error("This is an error message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelError, loggo.WithTimeProvider(fakeNow))
	logger.Error("This is an error log message")
}
Output:
2022-01-25 00:00:00 [ERROR]: This is an error log message

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...any)

Errorf logs a formatted message at the LevelError. If an error occurs while logging the message, it is ignored.

Parameters:

  • format: The format string for the error message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelError)
logger.Errorf("This is an error message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelError, loggo.WithTimeProvider(fakeNow))
	logger.Errorf("This is an error log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [ERROR]: This is an error log message with a "format"

func (*Logger) Fatal

func (l *Logger) Fatal(message string)

Fatal logs a message at the LevelFatal. If an error occurs while logging the message, it is ignored.

Parameters:

  • message: The fatal message to log.

Example:

logger := loggo.New(loggo.LevelFatal)
logger.Fatal("This is a fatal message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelFatal, loggo.WithTimeProvider(fakeNow))
	logger.Fatal("This is a fatal log message")
}
Output:
2022-01-25 00:00:00 [FATAL]: This is a fatal log message

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...any)

Fatalf logs a formatted message at the LevelFatal. If an error occurs while logging the message, it is ignored.

Parameters:

  • format: The format string for the fatal message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelFatal)
logger.Fatalf("This is a fatal message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelFatal, loggo.WithTimeProvider(fakeNow))
	logger.Fatalf("This is a fatal log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [FATAL]: This is a fatal log message with a "format"

func (*Logger) Info

func (l *Logger) Info(message string)

Info logs a message at the LevelInfo. If an error occurs while logging the message, it is ignored.

Parameters:

  • message: The info message to log.

Example:

logger := loggo.New(loggo.LevelInfo)
logger.Info("This is an info message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow))
	logger.Info("This is an info log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...any)

Infof logs a formatted message at the LevelInfo. If an error occurs while logging the message, it is ignored.

Parameters:

  • format: The format string for the info message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelInfo)
logger.Infof("This is an info message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow))
	logger.Infof("This is an info log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message with a "format"

func (*Logger) Log

func (l *Logger) Log(level Level, message string)

Log logs a message at the given log level. If the log level is below the Threshold, the message is not logged. If an error occurs while logging the message, it is ignored.

Parameters:

  • level: The log level of the message.
  • message: The message to log.

Example:

logger := loggo.New(loggo.LevelInfo)
logger.Log(loggo.LevelInfo, "This is an info message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message
Example (CallerProviderErr)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

var errorCallerProvider = func() (pc uintptr, file string, line int, ok bool) {
	return 0, "", 0, false
}

func main() {
	logger := loggo.New(
		loggo.LevelInfo,
		loggo.WithTimeProvider(fakeNow),
		loggo.WithTemplate("{{.Caller}} [{{.Level}}]: {{.Message}}"),
		loggo.WithCallerProvider(errorCallerProvider),
	)
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
unknown [INFO]: This is an info log message
Example (Context)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	ctx := context.WithValue(context.Background(), "trace_id", "123456")

	postHook := func(l *loggo.Logger, msg *string) {
		fmt.Printf("Trace ID: %q\n", l.Context.Value("trace_id"))
	}

	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithContext(ctx), loggo.WithPostHook(postHook))
	logger.Log(loggo.LevelInfo, "This is an info log message")
	logger.Fatal("This is a fatal log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message
Trace ID: "123456"
2022-01-25 00:00:00 [FATAL]: This is a fatal log message
Trace ID: "123456"
Example (MaxSize)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithMaxSize(10))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an
Example (PostHook)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	ctx := context.WithValue(context.Background(), "count", 0)
	preHook := func(l *loggo.Logger, msg *string) {
		*msg = fmt.Sprintf("%s, count: %d", *msg, l.Context.Value("count").(int))
	}

	postHook := func(l *loggo.Logger, msg *string) {
		count := l.Context.Value("count").(int)

		l.Context = context.WithValue(ctx, "count", count+1)
	}

	logger := loggo.New(
		loggo.LevelInfo,
		loggo.WithTimeProvider(fakeNow),
		loggo.WithPreHook(preHook),
		loggo.WithPostHook(postHook),
		loggo.WithContext(ctx),
	)
	logger.Log(loggo.LevelInfo, "This is an info log message")
	logger.Log(loggo.LevelFatal, "This is a fatal log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message, count: 0
2022-01-25 00:00:00 [FATAL]: This is a fatal log message, count: 1
Example (PreHook)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	preHook := func(l *loggo.Logger, msg *string) {
		l.Threshold = loggo.LevelWarn
	}

	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithPreHook(preHook))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Example (PreHookMessage)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	preHook := func(l *loggo.Logger, msg *string) {
		*msg = "This is a pre hook message"
	}

	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithPreHook(preHook))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is a pre hook message
Example (Template)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithTemplate("[{{.Level}}]: {{.Message}}"))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
[INFO]: This is an info log message
Example (TemplateComplete)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

var okCallerProvider = func() (pc uintptr, file string, line int, ok bool) {
	return 0, "file", 1, true
}

func main() {
	logger := loggo.New(
		loggo.LevelInfo,
		loggo.WithTimeProvider(fakeNow),
		loggo.WithTemplate("{{.Time}} {{.Caller}} | [{{.Level}}]: {{.Message}}"),
		loggo.WithCallerProvider(okCallerProvider),
	)
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
2022-01-25 00:00:00 file:1 | [INFO]: This is an info log message
Example (Threshold)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelWarn, loggo.WithTimeProvider(fakeNow))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Example (TimeFormat)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow), loggo.WithTimeFormat("02/01/06 00:00"))
	logger.Log(loggo.LevelInfo, "This is an info log message")
}
Output:
25/01/22 00:00 [ INFO]: This is an info log message

func (*Logger) LogE

func (l *Logger) LogE(level Level, message string) error

LogE logs a message at the given log level and returns an error if the message could not be logged. If the log level is below the Threshold, the message is not logged.

Parameters:

  • level: The log level of the message.
  • message: The message to log.

Returns:

  • An error if the message could not be logged, nil otherwise.

Example:

logger := loggo.New(loggo.LevelInfo)
err := logger.LogE(loggo.LevelInfo, "This is an info message")
if err != nil {
	log.Fatal(err)
}

func (*Logger) Logf

func (l *Logger) Logf(level Level, format string, args ...any)

Logf logs a formatted message at the given log level. If the log level is below the Threshold, the message is not logged. If an error occurs while logging the message, it is ignored.

Parameters:

  • level: The log level of the message.
  • format: The format string for the message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelInfo)
logger.Logf(loggo.LevelInfo, "This is an info message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(fakeNow))
	logger.Logf(loggo.LevelInfo, "This is an info log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [ INFO]: This is an info log message with a "format"
Example (Threshold)
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelWarn, loggo.WithTimeProvider(fakeNow))
	logger.Logf(loggo.LevelInfo, "This is an info log message with a %s", "format")
}

func (*Logger) LogfE

func (l *Logger) LogfE(level Level, format string, args ...any) error

LogfE logs a formatted message at the given log level and returns an error if the message could not be logged. If the log level is below the Threshold, the message is not logged.

Parameters:

  • level: The log level of the message.
  • format: The format string for the message.
  • args: The arguments for the format string.

Returns:

  • An error if the message could not be logged, nil otherwise.

Example:

logger := loggo.New(loggo.LevelInfo)
err := logger.LogfE(loggo.LevelInfo, "This is an info message with a %s", "format")
if err != nil {
	log.Fatal(err)
}

func (*Logger) Warn

func (l *Logger) Warn(message string)

Warn logs a message at the LevelWarn. If an error occurs while logging the message, it is ignored.

Parameters:

  • message: The warn message to log.

Example:

logger := loggo.New(loggo.LevelWarn)
logger.Warn("This is a warn message")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelWarn, loggo.WithTimeProvider(fakeNow))
	logger.Warn("This is a warn log message")
}
Output:
2022-01-25 00:00:00 [ WARN]: This is a warn log message

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...any)

Warnf logs a formatted message at the LevelWarn. If an error occurs while logging the message, it is ignored.

Parameters:

  • format: The format string for the warn message.
  • args: The arguments for the format string.

Example:

logger := loggo.New(loggo.LevelWarn)
logger.Warnf("This is a warn message with a %s", "format")
Example
package main

import (
	"time"

	"github.com/hvpaiva/loggo"
)

var fakeNow = func() time.Time {
	return time.Date(2022, 1, 25, 0, 0, 0, 0, time.UTC)
}

func main() {
	logger := loggo.New(loggo.LevelWarn, loggo.WithTimeProvider(fakeNow))
	logger.Warnf("This is a warn log message with a %q", "format")
}
Output:
2022-01-25 00:00:00 [ WARN]: This is a warn log message with a "format"

type Option

type Option func(*Logger)

Option is a function that configures a Logger.

func WithCallerProvider

func WithCallerProvider(provider CallerProvider) Option

WithCallerProvider configures the caller provider function of a Logger. The default caller provider is runtime.Caller.

Parameters:

  • provider: The CallerProvider function to use.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithCallerProvider(func(skip int) (pc uintptr, file string, line int, ok bool) {
	return runtime.Caller(skip)
}))

func WithContext added in v1.0.0

func WithContext(ctx context.Context) Option

WithContext configures the context of a Logger. The default context is context.Background.

Parameters:

  • Context: The context to use.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithContext(context.Background()))

func WithMaxSize

func WithMaxSize(size int) Option

WithMaxSize configures the maximum size of a log message. The default maximum size is 1000.

Parameters:

  • size: The maximum size of the log message.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithMaxSize(1000))

func WithOutput

func WithOutput(output io.Writer) Option

WithOutput configures the output destination of a Logger. The default output is os.Stdout.

Parameters:

  • output: The io.Writer to use as the output destination.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithOutput(os.Stderr))

func WithPostHook added in v1.0.0

func WithPostHook(hook Hook) Option

WithPostHook adds a post-hook to a Logger. Post-hooks are executed after logging a message.

Parameters:

  • hook: The post-hook function to add.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithPostHook(func(Context context.Context, level loggo.Level, message string) {
	// Do something after logging the message
}))

func WithPreHook added in v1.0.0

func WithPreHook(hook Hook) Option

WithPreHook adds a pre-hook to a Logger. Pre-hooks are executed before logging a message.

Parameters:

  • hook: The pre-hook function to add.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithPreHook(func(Context context.Context, level loggo.Level, message string) {
	// Do something before logging the message
}))

func WithTemplate

func WithTemplate(template string) Option

WithTemplate configures the log message template of a Logger. The default template is "{{.Time}} [{{printf \"%5s\" .Level}}]: {{.Message}}".

Parameters:

  • template: The template string for log messages.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithTemplate("{{.Time}}: {{.Message}}"))

func WithTimeFormat

func WithTimeFormat(format string) Option

WithTimeFormat configures the time format of a Logger. The default time format is "2006-01-02 15:04:05".

Parameters:

  • format: The format string for the time in the log message.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithTimeFormat("2006-01-02 15:04:05"))

func WithTimeProvider

func WithTimeProvider(provider TimeProvider) Option

WithTimeProvider configures the time provider function of a Logger. The default time provider is time.Now.

Parameters:

  • provider: The TimeProvider function to use.

Example:

logger := loggo.New(loggo.LevelInfo, loggo.WithTimeProvider(func() time.Time { return time.Unix(0, 0) }))

type TimeProvider

type TimeProvider func() time.Time

TimeProvider is a function that returns the current time.

Jump to

Keyboard shortcuts

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