logger

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2025 License: MIT Imports: 14 Imported by: 0

README

Logger Middleware for Go (net/http)

Logger is a Go package that provides a middleware for the standard net/http library to log every API request into a SQLite database. It also includes a lightweight web-based visualizer to browse and analyze logs. Built as a core net/http module, it can be integrated easily with frameworks like Echo or Gin via simple adapters.

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.
  • SQLite Backend: Stores logs in a durable SQLite database with WAL mode for reliability.
  • 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.
  • Configurable: Exclude routes/patterns, secure with password, customize themes and database path.
  • Framework-Agnostic: Core middleware uses net/http. Adapters provided for Echo and easily extendable to other frameworks.

Installation

go get github.com/ZiplEix/logger/v2

Usage

Core net/http
package main

import (
    "log"
    "net/http"

    "github.com/ZiplEix/logger/v2"
)

func main() {
    // 1) Create a ServeMux
    mux := http.NewServeMux()

    // 2) Initialize logger (creates DB, starts background worker)
    logger.SetupHTTP(mux, logger.Config{
        DatabasePath: "./logs.sqlite",
        // optional overrides: WorkerBufferSize, Path, Password, Theme, etc.
    })

    // 3) Wrap mux with logging middleware
    handler := logger.New()(mux)

    // 4) Application routes
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })

    // 5) Start server
    log.Fatal(http.ListenAndServe(":8080", handler))
}
Echo framework
package main

import (
	"github.com/ZiplEix/logger/v2"
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()

	e.Use(echo.WrapMiddleware(logger.New()))

	e.GET("/", func(c echo.Context) error {
		return c.String(200, "Hello, World!")
	})

	e.GET("/log", func(c echo.Context) error {
		logs, err := logger.GetAllLogs()
		if err != nil {
			return c.String(500, "Error retrieving logs: "+err.Error())
		}
		return c.JSON(200, logs)
	})

	logger.SetupEcho(e, logger.Config{})

	e.Logger.Fatal(e.Start(":8080"))
}
Important Notes
  1. Middleware Declaration Order: 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

View Source
var Theme = ThemeConfig{
	Light:        "light",
	Dark:         "dark",
	Cupcake:      "cupcake",
	Bumblebee:    "bumblebee",
	Emerald:      "emerald",
	Corporate:    "corporate",
	Synthwave:    "synthwave",
	Retro:        "retro",
	Cyberpunk:    "cyberpunk",
	Valentine:    "valentine",
	Halloween:    "halloween",
	Garden:       "garden",
	Forest:       "forest",
	Aqua:         "aqua",
	Lofi:         "lofi",
	Pastel:       "pastel",
	Fantasy:      "fantasy",
	Wireframe:    "wireframe",
	Black:        "black",
	Luxury:       "luxury",
	Dracula:      "dracula",
	Cmyk:         "cmyk",
	Autumn:       "autumn",
	Business:     "business",
	Acid:         "acid",
	Lemonade:     "lemonade",
	Night:        "night",
	Coffee:       "coffee",
	Winter:       "winter",
	Dim:          "dim",
	Nord:         "nord",
	Sunset:       "sunset",
	Caramellatte: "caramellatte",
	Abyss:        "abyss",
	Silk:         "silk",
}

Functions

func New

func New() func(http.Handler) http.Handler

func Setup

func Setup(mux *http.ServeMux, config Config)

func SetupEcho

func SetupEcho(e *echo.Echo, 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 request context
	//
	// 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: ThemeConfig.Dark
	// (see https://daisyui.com/theme-generator/)
	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)

type ThemeConfig

type ThemeConfig struct {
	Light        string
	Dark         string
	Cupcake      string
	Bumblebee    string
	Emerald      string
	Corporate    string
	Synthwave    string
	Retro        string
	Cyberpunk    string
	Valentine    string
	Halloween    string
	Garden       string
	Forest       string
	Aqua         string
	Lofi         string
	Pastel       string
	Fantasy      string
	Wireframe    string
	Black        string
	Luxury       string
	Dracula      string
	Cmyk         string
	Autumn       string
	Business     string
	Acid         string
	Lemonade     string
	Night        string
	Coffee       string
	Winter       string
	Dim          string
	Nord         string
	Sunset       string
	Caramellatte string
	Abyss        string
	Silk         string
}

Theme represents the theme of the logger.

It represent the daisyui themes.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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