logger

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2025 License: MIT Imports: 12 Imported by: 0

README

Logger Middleware for GoFiber

Logger is a Go package that extends the GoFiber framework by providing a middleware to log every API call into a SQLite database. Additionally, it includes a web-based visualizer to browse and analyze the logs.

Features

  • Automatic Logging: Logs every API request to a SQLite database, capturing details like IP address, URL, method, response status, latency, and more.
  • Web Visualizer: A built-in web interface for browsing and filtering logs.
  • Highly Configurable: Options to exclude specific routes or requests, secure log access with passwords, and customize storage paths.
  • Optional Visualizer: Use only the logging feature without enabling the web visualizer if desired.
  • Easy Integration: Seamlessly integrates with GoFiber applications.

Installation

To use Logger in your GoFiber project, add it to your dependencies:

go get github.com/ZiplEix/logger

Usage

Basic Example

Here’s an example of how to use Logger in your GoFiber application:

package main

import (
	"github.com/ZiplEix/logger"
	"github.com/gofiber/fiber/v2"
)

func main() {
	app := fiber.New()

	// Add the middleware
	app.Use(logger.New())

	// Example routes
	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World!")
	})

	app.Get("/log", func(c *fiber.Ctx) error {
		logs, err := logger.GetAllLogs()
		if err != nil {
			return c.SendString("Error retrieving logs: " + err.Error())
		}
		return c.JSON(logs)
	})

	// Set up the logger with default configuration
	// This is optional if you only want to log requests without the web visualizer.
	logger.Setup(app, logger.Config{})

	// Start the server
	app.Listen(":8080")
}
Important Notes
  1. Middleware Declaration Order: In GoFiber, the order of middleware declaration matters. Any routes declared before the logging middleware (logger.New()) will not be logged. Ensure you declare the middleware early in your application setup.

  2. Optional Visualizer: If you only want to log requests to the database and do not need the web visualizer, you can skip calling Setup(app, config). The middleware will still capture and store all logs in the SQLite database.


Configuration

The Config struct allows you to customize the Logger middleware. Here are the main configuration options:

type Config struct {
    DatabasePath         string   // Path for SQLite database (default: "./logs.sqlite")
    WorkerBufferSize     int      // Buffer size for log workers (default: 100)
    Path                 string   // Base path for logs view (default: "/logs")
    ExcludeRoutes        []string // Routes to exclude (default: ["/logs", "/favicon.ico"])
    ExcludePatterns      []string // Patterns to exclude (default: ["/logs/*"])
    SecureByPassword     *bool    // Secure logs view with password (default: true)
    Password             string   // Password for logs view (default: "password")
    JwtSecret            string   // Secret key for JWT tokens (default: "secret")
    JwtExpireTime        int64    // JWT token expiration time in seconds (default: 3600)
    Theme                string   // Theme for logs view (default: "dark")
}

Example of custom configuration:

logger.Setup(app, logger.Config{
    DatabasePath: "./custom_logs.sqlite",
    Path:         "/admin/logs",
    Password:     "mysecurepassword",
    Theme:        "light",
})

Web Visualizer

The Logger package includes a web-based visualizer to browse logs. By default, the visualizer is available at /logs. If secured with a password (default: "password"), you will be prompted to log in.

Web Visualizer Screenshot

Endpoints Added by Setup

Calling logger.Setup on your application adds the following four endpoints:

  1. GET /logs: Displays the logs web interface.
  2. GET /logs/all: Fetches all logs in JSON format.
  3. GET /logs/auth: Displays the login page for accessing the logs.
  4. POST /logs/auth: Handles user authentication for secured access.

If you do not need these endpoints or the visualizer, you can skip calling Setup.


Log Entry Structure

Logs are stored in a SQLite database in the following structure:

Field Type Description
ID int64 Unique log ID
IPAddress string IP address of the requester
Url string URL of the request
Action string HTTP method (GET, POST, etc.)
Details string Additional details about the request (optional)
Timestamp datetime Time the request was made
UserAgent string User-Agent header of the requester (optional)
Status string HTTP response status
Latency int64 Request processing time in milliseconds

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests to improve this project.


Author

Made with ❤️ by ZiplEix

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New() fiber.Handler

func Setup

func Setup(app *fiber.App, config Config)

Types

type Config

type Config struct {
	// DatabasePath define the location where the sqlite database wil be stored
	//
	// Optional. Default: ./logs.sqlite
	DatabasePath string

	// WorkerBufferSize define the size of the worker buffer
	//
	// Optional. Default: 100
	WorkerBufferSize int

	// Path define the the base path to the logs view
	// (it is recommended to use a path that is not publicly accessible)
	// (e.g. /logs or /admin/logs)
	//
	// If set manually, it is recommended to also set the ExcludeRoutes and ExcludePatterns
	//
	// Optional. Default: /logs
	Path string

	// ExcludePaths define the paths to exclude from logging
	//
	// Optional. Default: ["logs", "/favicon.ico"]
	ExcludeRoutes []string

	// ExcludePaths define the paths to exclude from logging
	//
	// Optional. Default: ["/logs/*"]
	ExcludePatterns []string

	// ExcludePAram define a parameter that will exclude the request from logging
	//
	// Optional. Default: ""
	ExcludeParam string

	// LogDetailMember define the member name that will be used to store the log details in the fiber.Ctx local
	//
	// Optional. Default: "logDetail"
	LogDetailMember string

	// SecureByPassword define if the logs view should be secured by a password
	//
	// Optional. Default: true
	SecureByPassword *bool

	// Password define the password to secure the logs view
	// (it is recommended to store it in an environment variable)
	//
	// Optional. Default: "password"
	Password string

	// JwtSecret define the secret to sign the JWT token
	// (it is recommended to store it in an environment variable)
	//
	// Optional. Default: "secret"
	JwtSecret string

	// JwtExpireTime define the expiration time of the JWT token in seconds
	//
	// Optional. Default: 3600
	// (1 hour)
	JwtExpireTime int64

	// Theme define the theme of the logs view
	//
	// Optional. Default: "dark"
	Theme string

	// JwtSigningMethod define the signing method to use for the JWT token
	//
	// Optional. Default: jwt.SigningMethodHS256
	JwtSigningMethod jwt.SigningMethod

	// AuthTokenCookieName define the name of the cookie that will be used to store the JWT token
	//
	// Optional. Default: "auth_token"
	AuthTokenCookieName string

	// IncludeLogPageConnexion define if the connexion via password to the logs page should be logged
	//
	// Optional. Default: true
	IncludeLogPageConnexion *bool
}

Config define the configuration for the logger middleware

It is recommended to use the default configuration and override only the values you need

type LogEntry

type LogEntry struct {
	ID        int64     `db:"id" json:"id"`
	IPAddress string    `db:"ip_address" json:"ip_address"`
	Url       string    `db:"url" json:"url"`
	Action    string    `db:"action" json:"action"`
	Details   *string   `db:"details" json:"details,omitempty"` // nullable, omis si nil
	Timestamp time.Time `db:"timestamp" json:"timestamp"`
	UserAgent *string   `db:"user_agent" json:"user_agent,omitempty"` // nullable, omis si nil
	Status    *string   `db:"status" json:"status,omitempty"`         // nullable, omis si nil
	Latency   int64     `db:"latency" json:"latency"`
}

func GetAllLogs

func GetAllLogs() ([]LogEntry, error)

func GetLogById

func GetLogById(id int64) (LogEntry, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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