logstore

package module
v1.24.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: GPL-3.0 Imports: 16 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Log Store

Tests Status Go Report Card PkgGoDev

Logs messages to a database table.

License

This project is licensed under the GNU General Public License version 3 (GPL-3.0). You can find a copy of the license at https://www.gnu.org/licenses/gpl-3.0.en.html

For commercial use, please use my contact page to obtain a commercial license.

Installation

go get -u github.com/dracory/logstore

Setup

logStore, err = logstore.NewStore(logstore.NewStoreOptions{
    DB: databaseInstance,
    LogTableName: "log",
    AutomigrateEnabled: true,
})

if err != nil {
    panic(error.Error())
}

Usage

logStore.Info("Hello")

// with additional context
logStore.InfoWithContext("Hello", map[string]string{
    "name": "John Doe"
})

Slog

As slog is the now official logger in golang, LogStore provides a SlogHandler.

Logger = *slog.New(logstore.NewSlogHandler(&LogStore))

logger.Info("Hello", "name", "John Doe")

Log Levels

  1. LevelTrace - Something very low level
  2. LevelDebug - Useful debugging information
  3. LevelInfo - Something noteworthy happened!
  4. LevelWarn - You should probably take a look at this
  5. LevelError - Something failed but I'm not quitting
  6. LevelFatal - Bye. Calls os.Exit(1) after logging
  7. LevelPanic - I'm bailing. Calls panic() after logging

Change Log

2024.09.23 - Added a SlogHandler

2023.07.19 - Updated instance creation to use options struct

2022.06.26 - Updated dependencies

2021.12.21 - Added LICENSE

2021.12.21 - Added test badge

2021.12.21 - Added support for DB dialects

2021.12.21 - Removed GORM dependency and moved to the standard library

Documentation

Index

Constants

View Source
const (
	// LevelTrace trace level
	LEVEL_TRACE = "trace"
	// LevelDebug debug level
	LEVEL_DEBUG = "debug"
	// LevelError error level
	LEVEL_ERROR = "error"
	// LevelFatal fatal level
	LEVEL_FATAL = "fatal"
	// LevelInfo info level
	LEVEL_INFO = "info"
	// LevelPanic panic level
	LEVEL_PANIC = "panic"
	// LevelWarning warning level
	LEVEL_WARNING = "warning"
)

Log levels

View Source
const COLUMN_CONTEXT = "context"
View Source
const COLUMN_ID = "id"
View Source
const COLUMN_LEVEL = "level"
View Source
const COLUMN_MESSAGE = "message"
View Source
const COLUMN_TIME = "time"
View Source
const SlogAsyncBufferSizeDefault = 4096

SlogAsyncBufferSizeDefault bounds the pending-record queue used by SlogAsyncHandler. Sized so a burst of log calls cannot exhaust memory; when full, new records are dropped rather than blocking the caller on a slow database write.

Variables

This section is empty.

Functions

This section is empty.

Types

type LogInterface added in v1.10.0

type LogInterface interface {
	GetID() string
	SetID(id string) LogInterface

	GetLevel() string
	SetLevel(level string) LogInterface

	GetMessage() string
	SetMessage(message string) LogInterface

	GetContext() string
	SetContext(context string) LogInterface

	GetTime() time.Time
	SetTime(t time.Time) LogInterface

	GetTimeCarbon() *carbon.Carbon
	SetTimeCarbon(t *carbon.Carbon) LogInterface
}

LogInterface defines the public API for a log entry

func NewLog added in v1.10.0

func NewLog() LogInterface

NewLog creates a new log with the current UTC time

func NewLogWithData added in v1.10.0

func NewLogWithData(id, level, message, context string, t time.Time) LogInterface

NewLogWithData creates a new log from existing values

type LogQueryInterface added in v1.10.0

type LogQueryInterface interface {
	// Validation method
	Validate() error

	IsIDSet() bool
	GetID() string
	SetID(id string) LogQueryInterface

	IsIDInSet() bool
	GetIDIn() []string
	SetIDIn(ids []string) LogQueryInterface

	IsLevelSet() bool
	GetLevel() string
	SetLevel(level string) LogQueryInterface

	IsLevelInSet() bool
	GetLevelIn() []string
	SetLevelIn(levels []string) LogQueryInterface

	IsMessageContainsSet() bool
	GetMessageContains() string
	SetMessageContains(term string) LogQueryInterface

	IsMessageNotContainsSet() bool
	GetMessageNotContains() string
	SetMessageNotContains(term string) LogQueryInterface

	IsContextContainsSet() bool
	GetContextContains() string
	SetContextContains(term string) LogQueryInterface

	IsContextNotContainsSet() bool
	GetContextNotContains() string
	SetContextNotContains(term string) LogQueryInterface

	IsTimeGteSet() bool
	GetTimeGte() string
	SetTimeGte(time string) LogQueryInterface

	IsTimeLteSet() bool
	GetTimeLte() string
	SetTimeLte(time string) LogQueryInterface

	IsLimitSet() bool
	GetLimit() int
	SetLimit(limit int) LogQueryInterface

	IsOffsetSet() bool
	GetOffset() int
	SetOffset(offset int) LogQueryInterface

	IsOrderBySet() bool
	GetOrderBy() string
	SetOrderBy(orderBy string) LogQueryInterface

	IsOrderDirectionSet() bool
	GetOrderDirection() string
	SetOrderDirection(orderDirection string) LogQueryInterface

	IsColumnsSet() bool
	GetColumns() []string
	SetColumns(columns []string) LogQueryInterface
}

LogQueryInterface defines the interface for querying logs

func LogQuery added in v1.10.0

func LogQuery() LogQueryInterface

LogQuery creates a new log query

type NewStoreOptions

type NewStoreOptions struct {
	LogTableName       string
	DB                 *sql.DB
	AutomigrateEnabled bool
	DebugEnabled       bool
}

NewStoreOptions define the options for creating a new log store

type SlogAsyncHandler added in v1.24.0

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

SlogAsyncHandler wraps SlogHandler and performs the real Handle work on a single background goroutine. SlogHandler issues a synchronous DB INSERT per record; calling it inline adds a database round-trip to every logged operation, which is expensive on request hot paths (e.g. a per-request access log).

Records are cloned before enqueueing (slog.Record shares its attrs backing array with the caller). A full queue drops the record and counts it — logging must never block or fail the caller.

WithAttrs/WithGroup children share the same queue and drain worker — Drain on any handler drains them all, and records logged after Drain are dropped silently. Drain must be called only once logging has stopped (typically during shutdown, before closing the database).

func NewSlogAsyncHandler added in v1.24.0

func NewSlogAsyncHandler(logStore StoreInterface) *SlogAsyncHandler

NewSlogAsyncHandler starts the drain worker and returns an async handler writing to the given log store. Call Drain on shutdown, before closing the underlying database, so buffered records are not written into a closed connection.

func NewSlogAsyncHandlerWithBuffer added in v1.24.0

func NewSlogAsyncHandlerWithBuffer(logStore StoreInterface, capacity int) *SlogAsyncHandler

NewSlogAsyncHandlerWithBuffer is NewSlogAsyncHandler with a custom queue capacity. Values <= 0 fall back to SlogAsyncBufferSizeDefault.

func (*SlogAsyncHandler) Drain added in v1.24.0

func (h *SlogAsyncHandler) Drain()

Drain stops accepting records and waits for the worker to flush all pending records to the wrapped handler. The queue is never closed — records logged after Drain are dropped silently (the closed flag is checked before enqueue, and a send that slips past the check lands in a queue nobody reads rather than panicking on a closed channel). Safe to call more than once.

func (*SlogAsyncHandler) DroppedCount added in v1.24.0

func (h *SlogAsyncHandler) DroppedCount() uint64

DroppedCount returns how many records were dropped because the queue was full.

func (*SlogAsyncHandler) Enabled added in v1.24.0

func (h *SlogAsyncHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*SlogAsyncHandler) Handle added in v1.24.0

func (h *SlogAsyncHandler) Handle(_ context.Context, record slog.Record) error

func (*SlogAsyncHandler) WithAttrs added in v1.24.0

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

func (*SlogAsyncHandler) WithGroup added in v1.24.0

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

type SlogHandler

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

func NewSlogHandler

func NewSlogHandler(logStore StoreInterface) *SlogHandler

func (*SlogHandler) Enabled

func (handler *SlogHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*SlogHandler) Handle

func (handler *SlogHandler) Handle(ctx context.Context, record slog.Record) error

func (*SlogHandler) WithAttrs

func (handler *SlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*SlogHandler) WithGroup

func (handler *SlogHandler) WithGroup(name string) slog.Handler

type StoreInterface

type StoreInterface interface {
	// GetDB returns the underlying *sql.DB
	GetDB() *sql.DB

	// GetLogTableName returns the log table name
	GetLogTableName() string
	// SetLogTableName sets the log table name
	SetLogTableName(logTableName string)

	// MigrateDown drops the log table
	MigrateDown(ctx context.Context, tx ...*sql.Tx) error

	// MigrateUp creates the log table
	MigrateUp(ctx context.Context, tx ...*sql.Tx) error

	// EnableDebug enables or disables debug mode
	EnableDebug(debug bool)

	// Log adds a log entry
	Log(logEntry LogInterface) error

	// Debug adds a debug log
	Debug(message string) error

	// DebugWithContext adds a debug log with context data
	DebugWithContext(message string, context interface{}) error

	// Error adds an error log
	Error(message string) error

	// ErrorWithContext adds an error log with context data
	ErrorWithContext(message string, context interface{}) error

	// Fatal adds a fatal log
	Fatal(message string) error

	// FatalWithContext adds a fatal log with context data
	FatalWithContext(message string, context interface{}) error

	// Info adds an info log
	Info(message string) error

	// InfoWithContext adds an info log with context data
	InfoWithContext(message string, context interface{}) error

	// Panic adds a panic log and calls panic(message) after logging
	Panic(message string)

	// PanicWithContext adds a panic log with context data and calls panic(message) after logging
	PanicWithContext(message string, context interface{})

	// Trace adds a trace log
	Trace(message string) error

	// TraceWithContext adds a trace log with context data
	TraceWithContext(message string, context interface{}) error

	// Warn adds a warn log
	Warn(message string) error

	// WarnWithContext adds a warn log with context data
	WarnWithContext(message string, context interface{}) error

	LogCount(ctx context.Context, query LogQueryInterface) (int64, error)
	LogCreate(ctx context.Context, logEntry LogInterface) error
	LogList(ctx context.Context, query LogQueryInterface) ([]LogInterface, error)
	LogDelete(ctx context.Context, logEntry LogInterface) error
	LogDeleteByID(ctx context.Context, id string) error
	LogDeleteByIDs(ctx context.Context, ids []string) error
	LogFindByID(ctx context.Context, id string) (LogInterface, error)
}

StoreInterface defines the interface for a log store

func NewStore

func NewStore(opts NewStoreOptions) (StoreInterface, error)

NewStore creates a new log store

Jump to

Keyboard shortcuts

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