logmonitor

package
v0.4.10 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2023 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package logmonitor provides structured, leveled logging utilities designed for web applications. It utilizes the zap logging library to facilitate structured logging and integrates seamlessly with the Gin web framework. The package includes middleware for logging HTTP or HTTPS requests, capturing key information such as response status, method, path, and processing time for each request.

Available Functions, Variables, and Types:

Variables:

  • Logger: A global *zap.Logger variable for logging throughout the application.

Functions:

  • SetLogger(logger *zap.Logger): Sets the global Logger variable to a specified zap.Logger.
  • NewBadRequestError(userMessage string, err error): Creates a new BadRequestError instance.
  • CreateLogFields(operation string, options ...LogFieldOption): Generates common log fields.
  • WithComponent(component string): Returns a LogFieldOption that adds a 'component' field.
  • WithID(id string): Returns a LogFieldOption that adds an 'id' field.
  • WithError(err error): Returns a LogFieldOption that adds an 'error' field.
  • WithSignal(signal os.Signal): Returns a LogFieldOption that adds a 'signal' field.
  • RequestLogger(logger *zap.Logger): Gin middleware that logs HTTP or HTTPS requests.

Types:

  • BadRequestError: Custom error type with a user-friendly message and an underlying error.
  • LogFieldOption: Function signature for options to create log fields.

Constants:

  • The package may also define constants for log categorization (not shown in the provided code).

Usage example:

func main() {
    router := gin.Default()
    router.Use(logmonitor.RequestLogger(logmonitor.Logger))
    // ... additional middleware and route setup ...
    router.Run(":8080")
}

Flushing Logs: It is crucial to flush any buffered log entries upon application termination to ensure all logs are committed to their intended destination. This is accomplished by invoking the Logger.Sync() method, typically in the main function using defer to guarantee execution even during an unexpected exit.

Flush logs on application exit example:

func main() {
    defer func() {
        if err := logmonitor.Logger.Sync(); err != nil {
            fmt.Fprintf(os.Stderr, "Failed to flush logs: %v\n", err)
        }
    }()
    // ... remainder of the main function ...
}

The RequestLogger middleware logs vital request details and should be included as part of the Gin router setup to capture request metrics in a structured log format.

Copyright (c) 2023 by H0llyW00dzZ

Index

Constants

This section is empty.

Variables

View Source
var Logger *zap.Logger

Logger is a global variable to access the zap logger throughout the logmonitor package. It is initialized with a default configuration and can be replaced using SetLogger.

Functions

func CreateLogFields added in v0.2.2

func CreateLogFields(operation string, options ...LogFieldOption) []zap.Field

CreateLogFields generates common log fields for use in various parts of the application.

func RequestLogger

func RequestLogger(logger *zap.Logger) gin.HandlerFunc

RequestLogger returns a gin.HandlerFunc (middleware) that logs requests using zap. It captures key metrics for each HTTP or HTTPS request, including the status code, method, path, and processing duration, and outputs them in a structured format. This middleware enhances the observability of the application by providing detailed request logs, which are essential for monitoring and debugging.

Upon receiving a request, it logs the following information:

  • Machine Start Time (the local time when the request is received by the server)
  • HTTP or HTTPS status code of the response
  • HTTP or HTTPS method of the request
  • Requested path
  • Duration taken to process the request

The logs are output in a structured format, making them easy to read and parse.

func SetLogger added in v0.1.7

func SetLogger(logger *zap.Logger)

SetLogger sets the logger instance for the package. This function allows for the replacement of the default logger with a customized one, enabling flexibility in logging configurations and output formats.

Types

type BadRequestError added in v0.1.10

type BadRequestError struct {
	UserMessage string
	Err         error
}

BadRequestError is a custom error type for bad requests. It includes a user-friendly message and the underlying error, providing context for logging and user feedback.

func NewBadRequestError added in v0.1.10

func NewBadRequestError(userMessage string, err error) *BadRequestError

NewBadRequestError creates a new instance of BadRequestError. This function is used to construct an error with a user-friendly message and an underlying error, which can be used to provide detailed error information while also giving a clear message to the end-user.

func (*BadRequestError) Error added in v0.1.10

func (e *BadRequestError) Error() string

Error returns the message of the underlying error. This method allows BadRequestError to satisfy the error interface, making it compatible with Go's built-in error handling.

type LogFieldOption added in v0.2.2

type LogFieldOption func() zap.Field

LogFieldOption defines a function signature for options that can be passed to createLogFields.

func WithAnyZapField added in v0.4.5

func WithAnyZapField(field zap.Field) LogFieldOption

WithAnyZapField returns a LogFieldOption that allows direct use of zap.Field with CreateLogFields. This is useful for adding fields that are not covered by the other With* functions.

Example:

logmonitor.CreateLogFields("operation hack the planet", WithAnyZapField(zap.Binary("H0llyW00dzZ", []byte("0x1337"))))

func WithComponent added in v0.2.2

func WithComponent(component string) LogFieldOption

WithComponent returns a LogFieldOption that adds a 'component' field to the log.

func WithError added in v0.2.2

func WithError(err error) LogFieldOption

WithError returns a LogFieldOption that adds an 'error' field to the log.

func WithID added in v0.2.2

func WithID(id string) LogFieldOption

WithID returns a LogFieldOption that adds an 'id' field to the log.

func WithSignal added in v0.2.6

func WithSignal(signal os.Signal) LogFieldOption

WithSignal returns a LogFieldOption that adds a 'signal' field to the log.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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