logger

package module
v0.0.0-...-a1f76b3 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2025 License: MIT Imports: 9 Imported by: 0

README

logger

logger is a Go library providing structured logging with support for development and production environments, including Google Cloud Logging integration.

Overview

This package simplifies logging in Go applications by providing a unified interface for both development and production environments. In development, logs are printed to the console in a human-readable format with colors and timestamps. In production, logs are sent to Google Cloud Logging with structured data.

Features

  • Easy setup for both development and production logging.
  • Structured logging with key-value pairs.
  • Supports log levels (DEBUG, INFO, WARN, ERROR).
  • Colorful console output in development.
  • Integration with Google Cloud Logging.
  • Error stack traces in development mode for easier debugging.

Installation

go get github.com/albeebe/service/pkg/logger

Usage

Setting up Development Logging
package main

import (
    "context"
    "log/slog"

    "github.com/albeebe/service/pkg/logger"
)

func main() {
    ctx := context.Background()

    config := logger.Config{
        Level: slog.LevelDebug, // Set desired log level
    }

    log, err := logger.NewDevelopmentLogger(ctx, config)
    if err != nil {
        panic(err)
    }

    // Use the logger
    log.Info("Application started", "version", "1.0.0")
    log.Debug("Debugging info", "details", "some debug info")
    log.Error("An error occurred", "error", err)
}
Setting up Google Cloud Logging
package main

import (
    "context"
    "log/slog"

    "github.com/albeebe/service/pkg/logger"
)

func main() {
    ctx := context.Background()

    config := logger.Config{
        GCPProjectID: "your-gcp-project-id",
        LogName:      "your-log-name",
        Level:        slog.LevelInfo, // Set desired log level
    }

    log, err := logger.NewGoogleCloudLogger(ctx, config)
    if err != nil {
        panic(err)
    }

    // Use the logger
    log.Info("Application started", "version", "1.0.0")
    log.Warn("Potential issue detected", "details", "some warning")
    log.Error("An error occurred", "error", err)
}

Configuration

Config Struct

The Config struct is used to configure the logger:

type Config struct {
    GCPProjectID string     // Google Cloud Project ID
    LogName      string     // Name of the log stream
    Level        slog.Level // Minimum log level to capture (e.g., DEBUG, INFO)
}
  • GCPProjectID: Required for Google Cloud Logging; specify your Google Cloud Project ID.
  • LogName: Required for Google Cloud Logging; specify the name of the log stream.
  • Level: Sets the minimum level of logs to capture.

Logging Levels

The logger supports the following log levels:

  • slog.LevelDebug: Debug-level messages, typically only of interest during development.
  • slog.LevelInfo: Informational messages that highlight the progress of the application.
  • slog.LevelWarn: Potentially harmful situations which still allow the application to continue running.
  • slog.LevelError: Error events that might still allow the application to continue running.

Flushing Logs

For production logging to Google Cloud, it's important to flush the logs before exiting the application to ensure all logs are properly sent.

if err := logger.FlushLogger(log); err != nil {
    panic(err)
}

Examples

Logging with Structured Data

You can include key-value pairs in your log messages:

log.Info("User login", "username", "johndoe", "method", "oauth")
Error Logging with Stack Trace (Development Mode)

In development mode, when logging errors, a stack trace is included to help with debugging:

err := errors.New("something went wrong")
log.Error("an error occurred", "error", err)

Outputs:

[11:10:53.442] [ERROR] something went wrong | error=an error occurred
   └── (file: /path/to/project/service/main.go, line: 86)
   └── (file: /path/to/project/service-demo/main.go, line: 61)

This will output the error message along with a stack trace showing the file and line numbers.

Prerequisites

Google Cloud Logging

To use Google Cloud Logging, you need:

  • A Google Cloud Platform project.
  • Proper authentication setup (e.g., service account with the Logging > Logs Writer role).
  • Application credentials configured in your environment (e.g., GOOGLE_APPLICATION_CREDENTIALS environment variable pointing to your service account key file).

License

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

Contributing

Contributions are welcome! Feel free to open an issue or submit a pull request with any proposed changes.

Documentation

Index

Constants

View Source
const (
	DebugColor = "\033[36m" // Cyan for Debug
	InfoColor  = "\033[32m" // Green for Info
	WarnColor  = "\033[33m" // Yellow for Warn
	ErrorColor = "\033[31m" // Red for Error
	ResetColor = "\033[0m"  // Reset to default terminal color
)

ANSI color codes for different log levels

Variables

This section is empty.

Functions

func FlushLogger

func FlushLogger(l *slog.Logger) error

FlushLogger attempts to flush the logs for the provided slog.Logger. It supports flushing for loggers using either GoogleCloudLoggingHandler or DevelopmentHandler. If the logger does not support flushing, an error is returned.

func NewDevelopmentLogger

func NewDevelopmentLogger(ctx context.Context, config Config) (*slog.Logger, error)

NewDevelopmentLogger sets up a logger for development environments using a custom slog handler. This logger prints log entries to the console in a human-readable format. It includes: - Timestamps with millisecond precision. - Log levels (DEBUG, INFO, WARN, ERROR) in brackets for easy identification. - The log message itself. - Structured key-value data (attributes) when provided, appended after the message. - For ERROR-level logs, a stack trace is included, showing the file and line number of the error origin. This logging setup is useful for local development as it makes it easier to spot issues, read structured data, and debug errors directly from the console output.

func NewGoogleCloudLogger

func NewGoogleCloudLogger(ctx context.Context, config Config) (*slog.Logger, error)

NewGoogleCloudLogger sets up a logger for Google Cloud Logging. It validates the provided configuration, initializes a Google Cloud Logging client, creates a custom slog handler for Google Cloud Logging, and returns an slog.Logger.

Types

type Config

type Config struct {
	GCPProjectID string     // GCPProjectID is the Google Cloud Project ID where logs will be sent.
	LogName      string     // LogName is the name of the log stream where entries will be written.
	Level        slog.Level // Level is the minimum log level that will be captured (e.g., DEBUG, INFO).
}

Config holds configuration details for setting up logging.

type DevelopmentHandler

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

DevelopmentHandler is a custom handler for slog used in development environments. It outputs logs to the console with formatted messages and structured data.

func (*DevelopmentHandler) Enabled

func (h *DevelopmentHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the provided log level is enabled for this handler.

func (*DevelopmentHandler) Flush

func (h *DevelopmentHandler) Flush() error

Flush is a required handler method for the slog.Handler interface. In a development environment, there is no buffered output to flush, so this method simply returns nil.

func (*DevelopmentHandler) Handle

func (h *DevelopmentHandler) Handle(ctx context.Context, r slog.Record) error

Handle processes log records for development use, printing them to the console with a timestamp, the appropriate color based on log level, and a reset color afterward. It also includes any structured key-value data associated with the log record. For error logs, it attempts to append the relevant file and line number where the log was generated.

func (*DevelopmentHandler) WithAttrs

func (h *DevelopmentHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs is required to satisfy the slog.Handler interface. This method would typically return a new handler with additional attributes, but since attribute handling is not needed, it returns the original handler unchanged.

func (*DevelopmentHandler) WithGroup

func (h *DevelopmentHandler) WithGroup(name string) slog.Handler

WithGroup is required to satisfy the slog.Handler interface. This method would typically return a new handler that groups log attributes, but since grouping is not needed, it returns the original handler unchanged.

type GoogleCloudLoggingHandler

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

GoogleCloudLoggingHandler is a custom handler for slog used to send logs to Google Cloud Logging.

func (*GoogleCloudLoggingHandler) Enabled

func (h *GoogleCloudLoggingHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the provided log level is enabled for this handler.

func (*GoogleCloudLoggingHandler) Flush

func (h *GoogleCloudLoggingHandler) Flush() error

Flush sends any buffered log entries to Google Cloud Logging and waits for all logs to be fully processed. It ensures that logs are properly flushed before shutting down the service or completing operations that depend on log delivery.

func (*GoogleCloudLoggingHandler) Handle

Handle processes a slog.Record by converting it into a Google Cloud Logging entry. It extracts the log message and any associated structured attributes (key-value pairs), maps the slog log level to Google Cloud Logging severity, and forwards the log entry to Google Cloud Logging.

func (*GoogleCloudLoggingHandler) WithAttrs

func (h *GoogleCloudLoggingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs is required to satisfy the slog.Handler interface. This method would typically return a new handler with additional attributes, but since attribute handling is not needed, it returns the original handler unchanged.

func (*GoogleCloudLoggingHandler) WithGroup

func (h *GoogleCloudLoggingHandler) WithGroup(name string) slog.Handler

WithGroup is required to satisfy the slog.Handler interface. This method would typically return a new handler that groups log attributes, but since grouping is not needed, it returns the original handler unchanged.

Jump to

Keyboard shortcuts

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