logharbour

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: Apache-2.0 Imports: 9 Imported by: 28

Documentation

Overview

Package logharbour is a comprehensive logging system. It supports different log levels, log types, and can encode log entries in JSON. It also provides a fallback mechanism in case the primary log writer fails.

Example

Example of using With prefixed methods to set various fields of the logger.

// Open a file for logging.
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
	log.Fatal(err)
}
defer file.Close()

// Create a fallback writer that uses the file as the primary writer and stdout as the fallback.
fallbackWriter := NewFallbackWriter(file, os.Stdout)

// Initialize the logger.
logger := NewLogger("MyApp", fallbackWriter)

// Create a new logger with various fields set.
logger = logger.WithModule("Module1").
	WithWho("John Doe").
	WithStatus(Success).
	WithRemoteIP("192.168.1.1")

// Use the new logger to log an activity.
logger.LogActivity("User logged in", map[string]any{"username": "john"})

// Log a data change entry.
logger.LogDataChange("User updated profile", ChangeInfo{
	Entity:    "User",
	Operation: "Update",
	Changes:   map[string]any{"email": "john@example.com"},
})

// Change logger priority at runtime.
logger.ChangePriority(Debug2)

// Log a debug entry.
logger.LogDebug("Debugging user session", DebugInfo{
	Variables: map[string]any{"sessionID": "12345"},
})
Output:

{
    "app_name": "MyApp",
    "module": "Module1",
    "priority": "Info",
    "who": "John Doe",
    "status": 1,
    "remote_ip": "192.168.1.1",
    "type": "Activity",
    "message": "User logged in",
    "data": {
        "username": "john"
    }
}
{
    "app_name": "MyApp",
    "module": "Module1",
    "priority": "Info",
    "who": "John Doe",
    "status": 1,
    "remote_ip": "192.168.1.1",
    "type": "Change",
    "message": "User updated profile",
    "data": {
        "entity": "User",
        "operation": "Update",
        "changes": {
            "email": "john@example.com"
        }
    }
}
{
    "app_name": "MyApp",
    "module": "Module1",
    "priority": "Debug2",
    "who": "John Doe",
    "status": 1,
    "remote_ip": "192.168.1.1",
    "type": "Debug",
    "message": "Debugging user session",
    "data": {
        "variables": {
            "sessionID": "12345"
        },
        "fileName": "main.go",
        "lineNumber": 30,
        "functionName": "main",
        "stackTrace": "...",
        "pid": 1234,
        "runtime": "go1.15.6"
    }
}

Index

Examples

Constants

View Source
const (
	LogPriorityDebug2  = "Debug2"
	LogPriorityDebug1  = "Debug1"
	LogPriorityDebug0  = "Debug0"
	LogPriorityInfo    = "Info"
	LogPriorityWarn    = "Warn"
	LogPriorityErr     = "Err"
	LogPriorityCrit    = "Crit"
	LogPrioritySec     = "Sec"
	LogPriorityUnknown = "Unknown"
)
View Source
const (
	LogTypeChange   = "Change"
	LogTypeActivity = "Activity"
	LogTypeDebug    = "Debug"
	LogTypeUnknown  = "Unknown"
)
View Source
const DefaultPriority = Info

Variables

This section is empty.

Functions

func GetDebugInfo

func GetDebugInfo(skip int) (fileName string, lineNumber int, functionName string, stackTrace string)

GetDebugInfo returns debug information including file name, line number, function name and stack trace. The 'skip' parameter determines how many stack frames to ascend, with 0 identifying the caller of GetDebugInfo.

Types

type ActivityInfo

type ActivityInfo any

ActivityInfo holds information about system activities like web service calls or function executions.

type ChangeInfo

type ChangeInfo struct {
	Entity    string         `json:"entity"`
	Operation string         `json:"operation"`
	Changes   map[string]any `json:"changes"`
}

ChangeInfo holds information about data changes such as creations, updates, or deletions.

type DebugInfo

type DebugInfo struct {
	Pid          int            `json:"pid"`
	Runtime      string         `json:"runtime"`
	FileName     string         `json:"fileName"`
	LineNumber   int            `json:"lineNumber"`
	FunctionName string         `json:"functionName"`
	StackTrace   string         `json:"stackTrace"`
	Variables    map[string]any `json:"variables"`
}

DebugInfo holds debugging information that can help in software diagnostics.

type FallbackWriter

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

FallbackWriter provides an io.Writer that automatically falls back to a secondary writer if the primary writer fails. It is also used if logentry is not valid so that we can still log erroneous entries without writing them to the primary writer.

func NewFallbackWriter

func NewFallbackWriter(primary, fallback io.Writer) *FallbackWriter

NewFallbackWriter creates a new FallbackWriter with a specified primary and fallback writer.

func (*FallbackWriter) Write

func (fw *FallbackWriter) Write(p []byte) (n int, err error)

Write attempts to write the byte slice to the primary writer, falling back to the secondary writer on error. It returns the number of bytes written and any error encountered that caused the write to stop early.

type LogEntry

type LogEntry struct {
	AppName        string      `json:"app_name"`         // Name of the application.
	System         string      `json:"system"`           // System where the application is running.
	Module         string      `json:"module"`           // The module or subsystem within the application
	Type           LogType     `json:"type"`             // Type of the log entry.
	Priority       LogPriority `json:"priority"`         // Severity level of the log entry.
	When           time.Time   `json:"when"`             // Time at which the log entry was created.
	Who            string      `json:"who"`              // User or service performing the operation.
	Op             string      `json:"op"`               // Operation being performed
	WhatClass      string      `json:"what_class"`       // Unique ID, name of the object instance on which the operation was being attempted
	WhatInstanceId string      `json:"what_instance_id"` // Unique ID, name, or other "primary key" information of the object instance on which the operation was being attempted
	Status         Status      `json:"status"`           // 0 or 1, indicating success (1) or failure (0), or some other binary representation
	RemoteIP       string      `json:"remote_ip"`        // IP address of the caller from where the operation is being performed.
	Message        string      `json:"message"`          // A descriptive message for the log entry.
	Data           any         `json:"data"`             // The payload of the log entry, can be any type.
}

LogEntry encapsulates all the relevant information for a log message.

type LogPriority

type LogPriority int

logPriority defines the severity level of a log message.

const (
	Debug2 LogPriority = iota + 1 // Debug2 represents extremely verbose debugging information.
	Debug1                        // Debug1 represents detailed debugging information.
	Debug0                        // Debug0 represents high-level debugging information.
	Info                          // Info represents informational messages.
	Warn                          // Warn represents warning messages.
	Err                           // Err represents error messages where operations failed to complete.
	Crit                          // Crit represents critical failure messages.
	Sec                           // Sec represents security alert messages.
)

func (LogPriority) MarshalJSON

func (lp LogPriority) MarshalJSON() ([]byte, error)

MarshalJSON is required by the encoding/json package. It converts the logPriority to its string representation and returns it as a JSON-encoded value.

func (LogPriority) String added in v0.5.0

func (lp LogPriority) String() string

String returns the string representation of the logPriority.

func (*LogPriority) UnmarshalJSON added in v0.5.0

func (lp *LogPriority) UnmarshalJSON(data []byte) error

type LogType

type LogType int

LogType defines the category of a log message.

const (
	// Change represents a log entry for data changes.
	Change LogType = iota + 1
	// Activity represents a log entry for activities such as web service calls.
	Activity
	// Debug represents a log entry for debug information.
	Debug
	// Unknown represents an unknown log type.
	Unknown
)

func (LogType) MarshalJSON

func (lt LogType) MarshalJSON() ([]byte, error)

MarshalJSON is required by the encoding/json package. It converts the LogType to its string representation and returns it as a JSON-encoded value.

func (LogType) String added in v0.5.0

func (lt LogType) String() string

String returns the string representation of the LogType.

func (*LogType) UnmarshalJSON added in v0.5.0

func (lt *LogType) UnmarshalJSON(data []byte) error

type Logger

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

Logger provides a structured interface for logging. It's designed for each goroutine to have its own instance. Logger is safe for concurrent use. However, it's not recommended to share a Logger instance across multiple goroutines.

If the writer is a FallbackWriter and validation of a log entry fails, the Logger will automatically write the invalid entry to the FallbackWriter's fallback writer. If writing to fallback writer also fails then it writes to STDERR.

The 'With' prefixed methods in the Logger are used to create a new Logger instance with a specific field set to a new value. These methods create a copy of the current Logger, then set the desired field to the new value, and finally return the new Logger. This approach provides a flexible way to create a new Logger with specific settings, without having to provide all settings at once or change the settings of an existing Logger.

func NewLogger

func NewLogger(appName string, writer io.Writer) *Logger

NewLogger creates a new Logger with the specified application name and writer. We recommend using NewLoggerWithFallback instead of this method.

func NewLoggerWithFallback

func NewLoggerWithFallback(appName string, fallbackWriter *FallbackWriter) *Logger

NewLoggerWithFallback creates a new Logger with a fallback writer. The fallback writer is used if the primary writer fails or if validation of a log entry fails.

func (*Logger) ChangePriority

func (l *Logger) ChangePriority(newPriority LogPriority)

ChangePriority changes the priority level of the Logger.

func (*Logger) Log added in v0.5.0

func (l *Logger) Log(message string)

Log logs a generic message as an activity event.

func (*Logger) LogActivity

func (l *Logger) LogActivity(message string, data ActivityInfo)

LogActivity logs an activity event.

func (*Logger) LogDataChange

func (l *Logger) LogDataChange(message string, data ChangeInfo)

LogDataChange logs a data change event.

func (*Logger) LogDebug

func (l *Logger) LogDebug(message string, data DebugInfo)

LogDebug logs a debug event.

func (*Logger) WithModule

func (l *Logger) WithModule(module string) *Logger

WithModule returns a new Logger with the 'module' field set to the specified value.

func (*Logger) WithOp

func (l *Logger) WithOp(op string) *Logger

WithOp returns a new Logger with the 'op' field set to the specified value.

func (*Logger) WithPriority

func (l *Logger) WithPriority(priority LogPriority) *Logger

WithPriority returns a new Logger with the 'priority' field set to the specified value.

func (*Logger) WithRemoteIP

func (l *Logger) WithRemoteIP(remoteIP string) *Logger

WithRemoteIP returns a new Logger with the 'remoteIP' field set to the specified value.

func (*Logger) WithStatus

func (l *Logger) WithStatus(status Status) *Logger

WithStatus returns a new Logger with the 'status' field set to the specified value.

func (*Logger) WithWhatClass

func (l *Logger) WithWhatClass(whatClass string) *Logger

WithWhatClass returns a new Logger with the 'whatClass' field set to the specified value.

func (*Logger) WithWhatInstanceId

func (l *Logger) WithWhatInstanceId(whatInstanceId string) *Logger

WithWhatInstanceId returns a new Logger with the 'whatInstanceId' field set to the specified value.

func (*Logger) WithWho

func (l *Logger) WithWho(who string) *Logger

WithWho returns a new Logger with the 'who' field set to the specified value.

type Status

type Status int
const (
	Success Status = iota
	Failure
)

Jump to

Keyboard shortcuts

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