logar

package module
v1.2.11 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: MIT Imports: 20 Imported by: 1

README

Logar

A lightweight, flexible management library for Go applications, providing logging, analytics, server actions, and more.

Features

  • Simple, intuitive API for all modules
  • Logging:
    • Multiple log levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL)
    • Output to console, file, or custom writers via proxies
    • Context-aware logging
  • Server Actions:
    • Define and trigger custom server-side functions remotely with strongly-typed parameters.
  • Analytics:
    • Track service metrics such as request latency, error rates, distribution of OS, browser and referers, and bandwidth.
  • Feature Flags:
    • Toggle and control application features through runtime-configurable flags with conditional logic.
  • Web UI:
    • View and manage logs through a web interface
    • Execute server actions remotely
    • View analytics dashboards
    • Manage feature flags and conditions
  • Context-aware operations

Installation

go get sadk.dev/logar

Quick Start

Logar provides a suite of tools. Here's a basic logging example:

package main

import (
  "sadk.dev/logar"
  // Import other necessary logar sub-packages for specific features
  // e.g., "sadk.dev/logar/logarweb" for the web UI
)

func main() {
  // Create a new Logar application instance
  // The New() function accepts various configuration options for logging,
  // analytics, actions, web panel, etc.
  app, err := logar.New(
    logar.WithAppName("My Awesome App"), // Sets the application name
    logar.AddModel("System Logs", "system-logs"),
    logar.AddModel("User Activity", "user-activity"),

    // Add a console proxy to output all logs to terminal
    // logar.AddProxy(proxy.NewProxy(
    //   consolelogger.New(),
    //   proxy.NewFilter(),
    // )),
    // For the web UI, actions, and analytics, additional setup is required.
    // See the examples directory for detailed demonstrations.
  )
  if err != nil {
    // Handle error
  }

  // Basic logging
  app.GetLogger().Info("system-logs", "App Started. No errors", "startup")

  // To explore server actions, analytics, feature flags, and the web UI,
  // please refer to the detailed examples in the 'examples/' directory
  // in the project repository.
}

Configuration

Logar is configured using functional options with the logar.New() constructor.

// Configure Logar with various options
app, err := logar.New(
  logar.WithAppName("My App"),
  logar.WithDatabase("logs.db"), // For persisting logs and analytics data
  logar.WithAdminCredentials("admin", "securepassword"), // For web UI authentication

  // Logging specific configurations
  logar.AddModel("System Events", "system-events"),

  // Action specific configurations
  logar.WithAction("Server/Echo", "Description of action", func(message string) string {
    // Action logic here
    return "Result: " + message
  }),

  // Analytics can be automatically collected via middleware
  // Or events can be registered manually:
  // app.GetAnalytics().RegisterEvent(...)


  // Forwards logs to the proxy based on given filters (example)
  // logar.AddProxy(proxy.NewProxy(
  //   consolelogger.New(),
  //   proxy.NewFilter(),
  // )),

  // Conditional options
  logar.If(env == "test",
    logar.WithDatabase("test.db"),
  ),

  logar.IfElse(env == "prod",
    logar.WithDatabase("prod.db"),
    logar.WithDatabase("dev.db"),
  )
)
if err != nil {
  // Handle error
}

// Access different modules:
logger := app.GetLogger()
analyticsEngine := app.GetAnalytics()
actionManager := app.GetActionManager()
featureFlagManager := app.GetFeatureFlags()

// Start the web server (typically using net/http or a framework like Echo)
// and integrate logarweb.ServeHTTP for the Logar web panel.
// e.g., e.Any("/logar/*", echo.WrapHandler(logarweb.ServeHTTP("http://localhost:3000", "/logar", app)))

Advanced Usage & Examples

For detailed examples covering logging, the web UI, server actions, analytics, feature flags, and integrations with web frameworks like Echo, see the examples/ directory in the GitHub repository.

See the documentation for more API details.

License

MIT

Contributing

If you'd like to contribute to the project, please open an issue on GitHub to discuss your ideas or report bugs.

Warning: This project does not currently adhere strictly to semver, and API compatibility is not guaranteed between minor and patch updates.

Known Issues

  • ...

Documentation

Index

Constants

Variables

This section is empty.

Functions

func GetTablePrefix

func GetTablePrefix() string

func SetTablePrefix

func SetTablePrefix(prefix string)

func Severity

func Severity(severity int) models.Severity

Types

type Action

type Action struct {
	Path        string
	Func        interface{}
	Description string
}

type ActionManager

type ActionManager interface {
	Common

	InvokeAction(path string, args ...any) ([]any, error)
	GetActionArgTypes(path string) ([]reflect.Type, error)
	GetActionsMap() Actions
	GetAllActions() []string
	GetActionDetails(path string) (Action, bool)
	AddAction(action Action)
	RemoveAction(path string)
}

type ActionManagerImpl

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

func (*ActionManagerImpl) AddAction

func (a *ActionManagerImpl) AddAction(action Action)

func (*ActionManagerImpl) GetActionArgTypes

func (a *ActionManagerImpl) GetActionArgTypes(path string) ([]reflect.Type, error)

func (*ActionManagerImpl) GetActionDetails

func (a *ActionManagerImpl) GetActionDetails(path string) (Action, bool)

func (*ActionManagerImpl) GetActionsMap

func (a *ActionManagerImpl) GetActionsMap() Actions

func (*ActionManagerImpl) GetAllActions

func (a *ActionManagerImpl) GetAllActions() []string

func (*ActionManagerImpl) GetApp

func (a *ActionManagerImpl) GetApp() App

func (*ActionManagerImpl) InvokeAction

func (a *ActionManagerImpl) InvokeAction(path string, args ...any) ([]any, error)

func (*ActionManagerImpl) RemoveAction

func (a *ActionManagerImpl) RemoveAction(path string)

type Actions

type Actions []Action

type Analytics

type Analytics interface {
	// ID is automatically generated.
	RegisterRequest(log models.RequestLog) error

	GetStatistics(startTime time.Time, endTime time.Time) (AnalyticsSummary, error)
}

type AnalyticsImpl

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

func (*AnalyticsImpl) GetApp

func (a *AnalyticsImpl) GetApp() App

func (*AnalyticsImpl) GetStatistics

func (a *AnalyticsImpl) GetStatistics(startTime time.Time, endTime time.Time) (AnalyticsSummary, error)

func (*AnalyticsImpl) RegisterRequest

func (a *AnalyticsImpl) RegisterRequest(log models.RequestLog) error

type AnalyticsSummary

type AnalyticsSummary struct {
	TotalVisits      int64              `json:"total_visits"`       // Total number of requests received.
	UniqueVisitors   int64              `json:"unique_visitors"`    // Number of unique visitor IDs.
	ActiveVisitors   int64              `json:"active_visitors"`    // Number of active visitors (last 5 minutes)
	ErrorRate        float64            `json:"error_rate"`         // Rate of requests that are errors (e.g., 0.05 for 5%).
	AverageLatencyMs float64            `json:"average_latency_ms"` // Average request latency in milliseconds.
	P95LatencyMs     int64              `json:"p95_latency_ms"`     // 95th percentile request latency in milliseconds.
	P99LatencyMs     int64              `json:"p99_latency_ms"`     // 99th percentile request latency in milliseconds.
	TotalBytesSent   int64              `json:"total_bytes_sent"`   // Total bytes sent
	TotalBytesRecv   int64              `json:"total_bytes_recv"`   // Total bytes received
	TopPages         []PageStats        `json:"top_pages"`          // Top 5 most visited pages
	OSUsage          map[string]float64 `json:"os_usage"`           // OS usage distribution
	BrowserUsage     map[string]float64 `json:"browser_usage"`      // Browser usage distribution
	RefererUsage     map[string]float64 `json:"referer_usage"`      // Referer distribution
	InstanceStats    map[string]float64 `json:"instance_stats"`     // Request distribution by instance
}

type App

type App interface {
	GetLogger() Logger
	GetActionManager() ActionManager
	GetWebPanel() WebPanel
	GetAnalytics() Analytics
	GetFeatureFlags() FeatureFlags

	Close() error
	GetAllModels() LogModels
	SetTypeKind(type_ reflect.Type, kind TypeKind)
	SetTypeKindString(type_ string, kind TypeKind)
	GetTypeKind(type_ reflect.Type) (TypeKind, bool)
	GetTypeKindString(type_ string) (TypeKind, bool)

	PrepareContext(parent context.Context, values Map) context.Context
	GetContextValues(ctx context.Context) (Map, bool)
	GetFromContext(ctx context.Context, key string) (any, bool)
	AddContextValue(ctx context.Context, key string, value any) App

	IsSSEEnabled() bool
}

App is the main struct that contains library data for things like logging, actions, etc.

func New

func New(opts ...ConfigOpt) (App, error)

type AppImpl

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

func (*AppImpl) AddContextValue

func (l *AppImpl) AddContextValue(ctx context.Context, key string, value any) App

func (*AppImpl) Close

func (l *AppImpl) Close() error

func (*AppImpl) DeleteGlobal

func (l *AppImpl) DeleteGlobal(key string) error

func (*AppImpl) DeleteLogs

func (l *AppImpl) DeleteLogs(q *Query) error

func (*AppImpl) GetActionManager

func (l *AppImpl) GetActionManager() ActionManager

func (*AppImpl) GetAllGlobals

func (l *AppImpl) GetAllGlobals() ([]models.Global, error)

func (*AppImpl) GetAllModels

func (l *AppImpl) GetAllModels() LogModels

func (*AppImpl) GetAnalytics

func (l *AppImpl) GetAnalytics() Analytics

func (*AppImpl) GetContextValues

func (l *AppImpl) GetContextValues(ctx context.Context) (Map, bool)

func (*AppImpl) GetFeatureFlags

func (l *AppImpl) GetFeatureFlags() FeatureFlags

func (*AppImpl) GetFromContext

func (l *AppImpl) GetFromContext(ctx context.Context, key string) (any, bool)

func (*AppImpl) GetGlobal

func (l *AppImpl) GetGlobal(key string) (models.Global, error)

func (*AppImpl) GetGlobalBool

func (l *AppImpl) GetGlobalBool(key string) (bool, error)

func (*AppImpl) GetGlobalFloat

func (l *AppImpl) GetGlobalFloat(key string) (float64, error)

func (*AppImpl) GetGlobalInt

func (l *AppImpl) GetGlobalInt(key string) (int64, error)

func (*AppImpl) GetGlobalString

func (l *AppImpl) GetGlobalString(key string) (string, error)

func (*AppImpl) GetGlobalValue

func (l *AppImpl) GetGlobalValue(key string, out any) error

func (*AppImpl) GetLogger

func (l *AppImpl) GetLogger() Logger

func (*AppImpl) GetLogs

func (l *AppImpl) GetLogs(q *Query) ([]models.Log, error)

func (*AppImpl) GetTypeKind

func (l *AppImpl) GetTypeKind(type_ reflect.Type) (TypeKind, bool)

func (*AppImpl) GetTypeKindString

func (l *AppImpl) GetTypeKindString(type_ string) (TypeKind, bool)

func (*AppImpl) GetWebPanel

func (l *AppImpl) GetWebPanel() WebPanel

func (*AppImpl) IsSSEEnabled added in v1.2.10

func (l *AppImpl) IsSSEEnabled() bool

func (*AppImpl) NewTimer

func (l *AppImpl) NewTimer() *Timer

func (*AppImpl) PrepareContext

func (l *AppImpl) PrepareContext(parent context.Context, values Map) context.Context

func (*AppImpl) SetGlobal

func (l *AppImpl) SetGlobal(key string, value any, exported bool) error

func (*AppImpl) SetTypeKind

func (l *AppImpl) SetTypeKind(type_ reflect.Type, kind TypeKind)

func (*AppImpl) SetTypeKindString

func (l *AppImpl) SetTypeKindString(type_ string, kind TypeKind)

type AuthFunc

type AuthFunc func(r *http.Request) bool

type Common

type Common interface {
	GetApp() App
}

type Config

type Config struct {
	AppName         string
	Database        gorm.Dialector
	RequireAuth     bool
	AuthFunc        AuthFunc
	Models          LogModels
	MainFilter      logfilter.Filter
	Proxies         []proxy.Proxy
	Actions         Actions
	AdminUsername   string
	AdminPassword   string
	DefaultLanguage Language
	WebPanelConfig  WebPanelConfig
	SSEEnabled      bool
}

type ConfigOpt

type ConfigOpt func(*Config)

func AddModel

func AddModel(displayName string, modelId Model, icon ...string) ConfigOpt

func AddProxy

func AddProxy(proxy proxy.Proxy) ConfigOpt

func Combine

func Combine(opts ...ConfigOpt) ConfigOpt

func If

func If(condition bool, opts ...ConfigOpt) ConfigOpt

func IfElse

func IfElse(condition bool, ifOpts ConfigOpt, elseOpts ...ConfigOpt) ConfigOpt

func SetModels added in v1.2.4

func SetModels(models LogModels) ConfigOpt

func WithAction

func WithAction(path string, description string, action interface{}) ConfigOpt

func WithAdminCredentials

func WithAdminCredentials(username, password string) ConfigOpt

func WithAppName

func WithAppName(appName string) ConfigOpt

func WithAuth

func WithAuth(authFunc AuthFunc) ConfigOpt

func WithDatabase

func WithDatabase(database gorm.Dialector) ConfigOpt

func WithDefaultLanguage

func WithDefaultLanguage(language Language) ConfigOpt

func WithMainFilter added in v1.2.10

func WithMainFilter(filter logfilter.Filter) ConfigOpt

func WithSSEEnabled added in v1.2.10

func WithSSEEnabled(enabled bool) ConfigOpt

func WithWebPanelConfig added in v1.2.4

func WithWebPanelConfig(opts ...WebPanelConfigOpt) ConfigOpt

type FeatureFlags

type FeatureFlags interface {
	Common

	HasFeatureFlag(ctx context.Context, flag string) (bool, error)

	GetFeatureFlags() ([]models.FeatureFlag, error)
	GetFeatureFlagByName(name string) (models.FeatureFlag, error)
	GetFeatureFlag(id uint) (models.FeatureFlag, error)
	CreateFeatureFlag(flag *models.FeatureFlag) error
	UpdateFeatureFlag(flag *models.FeatureFlag) error
	DeleteFeatureFlag(id uint) error
}

type FeatureFlagsImpl

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

func (*FeatureFlagsImpl) CreateFeatureFlag

func (f *FeatureFlagsImpl) CreateFeatureFlag(flag *models.FeatureFlag) error

func (*FeatureFlagsImpl) DeleteFeatureFlag

func (f *FeatureFlagsImpl) DeleteFeatureFlag(id uint) error

func (*FeatureFlagsImpl) GetApp

func (f *FeatureFlagsImpl) GetApp() App

func (*FeatureFlagsImpl) GetFeatureFlag

func (f *FeatureFlagsImpl) GetFeatureFlag(id uint) (models.FeatureFlag, error)

func (*FeatureFlagsImpl) GetFeatureFlagByName

func (f *FeatureFlagsImpl) GetFeatureFlagByName(name string) (models.FeatureFlag, error)

func (*FeatureFlagsImpl) GetFeatureFlags

func (f *FeatureFlagsImpl) GetFeatureFlags() ([]models.FeatureFlag, error)

func (*FeatureFlagsImpl) HasFeatureFlag

func (f *FeatureFlagsImpl) HasFeatureFlag(ctx context.Context, flag string) (bool, error)

func (*FeatureFlagsImpl) UpdateFeatureFlag

func (f *FeatureFlagsImpl) UpdateFeatureFlag(flag *models.FeatureFlag) error

type Language

type Language string
const (
	English     Language = "en"
	Chinese     Language = "zh"
	Russian     Language = "ru"
	Turkish     Language = "tr"
	Kazakh      Language = "kk"
	Azerbaijani Language = "az"
)

type LogModel

type LogModel struct {
	DisplayName string `json:"displayName"`
	Identifier  Model  `json:"identifier"`
	Icon        string `json:"icon"` // FontAwesome icon name. default: "fa-solid fa-cube"
}

type LogModels

type LogModels []LogModel

type Logger

type Logger interface {
	Common
	WithContext(ctx context.Context) Logger

	Print(model Model, message any, category string, severity models.Severity) error
	Log(model Model, message any, category string) error
	Info(model Model, message any, category string) error
	Warn(model Model, message any, category string) error
	Error(model Model, message any, category string) error
	Fatal(model Model, message any, category string) error
	Trace(model Model, message any, category string) error

	NewTimer() *Timer
}

type LoggerImpl

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

func (*LoggerImpl) Error

func (l *LoggerImpl) Error(model Model, message any, category string) error

func (*LoggerImpl) Fatal

func (l *LoggerImpl) Fatal(model Model, message any, category string) error

func (*LoggerImpl) GetApp

func (l *LoggerImpl) GetApp() App

func (*LoggerImpl) Info

func (l *LoggerImpl) Info(model Model, message any, category string) error

func (*LoggerImpl) Log

func (l *LoggerImpl) Log(model Model, message any, category string) error

func (*LoggerImpl) NewTimer

func (l *LoggerImpl) NewTimer() *Timer

func (*LoggerImpl) Print

func (l *LoggerImpl) Print(model Model, message any, category string, severity models.Severity) error

func (*LoggerImpl) Trace

func (l *LoggerImpl) Trace(model Model, message any, category string) error

func (*LoggerImpl) Warn

func (l *LoggerImpl) Warn(model Model, message any, category string) error

func (*LoggerImpl) WithContext

func (l *LoggerImpl) WithContext(ctx context.Context) Logger

type Map

type Map map[string]any

type Model

type Model models.Model
const (
	LogarLogs Model = "logar.logs"
)

type PageStats

type PageStats struct {
	Path       string  `json:"path"`
	Visits     int64   `json:"visits"`
	Percentage float64 `json:"percentage"`
}

Statistics for a single page

type PaginationStrategy

type PaginationStrategy int
const (
	PaginationStatus_None PaginationStrategy = iota
	PaginationStatus_Cursor
	PaginationStatus_Offset
)

type Query added in v1.2.4

type Query struct {
	Options *QueryOptions
}

func NewQuery added in v1.2.4

func NewQuery() *Query

func (*Query) After added in v1.2.4

func (q *Query) After(from time.Time) *Query

func (*Query) Before added in v1.2.4

func (q *Query) Before(to time.Time) *Query

func (*Query) MessageContaints added in v1.2.4

func (q *Query) MessageContaints(text string) *Query

func (*Query) WithCategory added in v1.2.4

func (q *Query) WithCategory(category string) *Query

func (*Query) WithCursorPagination added in v1.2.4

func (q *Query) WithCursorPagination(cursor int, limit int) *Query

func (*Query) WithFilter added in v1.2.4

func (q *Query) WithFilter(filter models.Filter) *Query

func (*Query) WithIDGreaterThan added in v1.2.4

func (q *Query) WithIDGreaterThan(id uint) *Query

func (*Query) WithIDs added in v1.2.4

func (q *Query) WithIDs(ids ...uint) *Query

func (*Query) WithModel added in v1.2.4

func (q *Query) WithModel(model string) *Query

func (*Query) WithOffsetPagination added in v1.2.4

func (q *Query) WithOffsetPagination(offset int, page int) *Query

func (*Query) WithSeverity added in v1.2.4

func (q *Query) WithSeverity(severity models.Severity) *Query

func (*Query) WithTimeRange added in v1.2.4

func (q *Query) WithTimeRange(from time.Time, to time.Time) *Query

type QueryOptions

type QueryOptions struct {
	Model              string
	Category           string
	MessageContains    []string
	Filters            []models.Filter
	Severity           models.Severity
	PaginationStrategy PaginationStrategy
	Limit              int
	Page               int
	Cursor             int
	From               *time.Time
	To                 *time.Time
	IDs                []uint
	IDGreaterThan      uint
}

type Timer

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

func (*Timer) Elapsed

func (t *Timer) Elapsed() time.Duration

func (*Timer) Log

func (t *Timer) Log(model Model, message string, category string) error

func (*Timer) Reset

func (t *Timer) Reset()

func (*Timer) StartTime

func (t *Timer) StartTime() time.Time

type TypeKind

type TypeKind string
const (
	TypeKind_Text     TypeKind = "text"
	TypeKind_Int      TypeKind = "int"
	TypeKind_Float    TypeKind = "float"
	TypeKind_Bool     TypeKind = "bool"
	TypeKind_Time     TypeKind = "time"
	TypeKind_Duration TypeKind = "duration"
)

type WebPanel

type WebPanel interface {
	Common

	LoginUser(username, password string) (models.User, error)
	CreateUser(username, displayName, password string, isAdmin bool) (models.User, error)
	GetUser(id uint) (models.User, error)
	GetAllUsers() ([]models.User, error)
	UpdateUser(user models.User) error
	CreateSession(user models.User, device string) (string, error)
	DeleteSession(token string) error
	GetSession(token string) (*models.Session, error)
	GetActiveSessions(userID uint) ([]models.Session, error)
	GetDefaultLanguage() Language
	Auth(r *http.Request) bool
}

type WebPanelConfig added in v1.2.4

type WebPanelConfig struct {
	SessionDuration time.Duration
}

type WebPanelConfigOpt added in v1.2.4

type WebPanelConfigOpt func(*WebPanelConfig)

func WithSessionDuration added in v1.2.4

func WithSessionDuration(duration time.Duration) WebPanelConfigOpt

type WebPanelImpl

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

func (*WebPanelImpl) Auth

func (w *WebPanelImpl) Auth(r *http.Request) bool

func (*WebPanelImpl) CreateSession

func (w *WebPanelImpl) CreateSession(user models.User, device string) (string, error)

func (*WebPanelImpl) CreateUser

func (w *WebPanelImpl) CreateUser(username, displayName, password string, isAdmin bool) (models.User, error)

func (*WebPanelImpl) DeleteSession

func (w *WebPanelImpl) DeleteSession(token string) error

func (*WebPanelImpl) GetActiveSessions

func (w *WebPanelImpl) GetActiveSessions(userID uint) ([]models.Session, error)

func (*WebPanelImpl) GetAllUsers

func (w *WebPanelImpl) GetAllUsers() ([]models.User, error)

func (*WebPanelImpl) GetApp

func (w *WebPanelImpl) GetApp() App

func (*WebPanelImpl) GetDefaultLanguage

func (w *WebPanelImpl) GetDefaultLanguage() Language

func (*WebPanelImpl) GetSession

func (w *WebPanelImpl) GetSession(token string) (*models.Session, error)

func (*WebPanelImpl) GetUser

func (w *WebPanelImpl) GetUser(id uint) (models.User, error)

func (*WebPanelImpl) LoginUser

func (w *WebPanelImpl) LoginUser(username, password string) (models.User, error)

func (*WebPanelImpl) UpdateUser

func (w *WebPanelImpl) UpdateUser(user models.User) error

Directories

Path Synopsis
examples
actions command
analytics command
featureflags command
gormlogger command
logger command
main command
minimal command
proxy command
internal

Jump to

Keyboard shortcuts

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