Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async logger #30

Merged
merged 7 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/architecture/diagrams/plantuml/class_diagram.plantuml
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,28 @@ package pkg {
+ Critical(message : string, parameters : ...any)
+ Emergency(message : string, parameters : ...any)
}
struct baseAsyncLogger implements baseLoggerInterface {
~ *baseLogger
~ messageQueue : chan logrecord.Interface
~ waitGroup sync.WaitGroup
~ startListeningMessages()
+ WaitToFinishLogging()
+ Open(queueSize : int)
+ Close()
+ Log(level : level.Level, message : string, parameters : ...any)
}
interface AsyncLoggerInterface extends Interface {
+ Interface
+ WaitToFinishLogging()
+ Open(queueSize : int)
+ Close()
}
struct AsyncLogger implements AsyncLoggerInterface {
+ *Logger
+ WaitToFinishLogging()
+ Open(queueSize : int)
+ Close()
}
struct Configuration {
~ fromLevel : level.Level
~ toLevel : level.Level
Expand All @@ -243,6 +265,7 @@ package pkg {
~ template : string
~ init()
+ New(name : string, timeFormat : string) : *Logger
+ NewAsyncLogger(name : string, timeFormat : string, queueSize : int) : *AsyncLogger
+ WithFromLevel(fromLevel : level.Level) : Option
+ WithToLevel(toLevel : level.Level) : Option
+ WithTemplate(template : string) : Option
Expand All @@ -268,7 +291,9 @@ package pkg {
+ Emergency(message : string, parameters : ...any)
}

baseAsyncLogger *-- baseLogger
Logger *-- baseLoggerInterface
AsyncLogger *-- Logger
"<<module>>" ..> Logger : uses
"<<module>>" ..> Option : uses
"<<module>>" ..> Configuration : uses
Expand Down
Binary file modified docs/architecture/diagrams/png/class_diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2,442 changes: 1,302 additions & 1,140 deletions docs/architecture/diagrams/svg/class_diagram.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 13 additions & 2 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,24 @@

This package contains examples how to use logger.

## customasynclogger

Demonstrates how to create a new custom logger for the application.

It creates an async logger with provided queue size that writes messages on the console asynchronously. It also provides
an example how to wait for all messages to be written.

## customlogger

Demonstrates how to create a new custom logger for the application. It creates a simple logger that writes messages on the console.
Demonstrates how to create a new custom logger for the application.

It creates a simple logger that writes messages on the console.

## customstructuredlogger

Demonstrates how to create a new custom logger for the application. It creates a simple logger that writes messages on the console in structured format.
Demonstrates how to create a new custom logger for the application.

It creates a simple logger that writes messages on the console in structured format.

## defaultlogger

Expand Down
29 changes: 29 additions & 0 deletions examples/customasynclogger/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Example that shows how to create and use custom async logger.
package main

import (
"fmt"
"github.com/dl1998/go-logging/pkg/common/level"
"github.com/dl1998/go-logging/pkg/logger"
"github.com/dl1998/go-logging/pkg/logger/formatter"
"github.com/dl1998/go-logging/pkg/logger/handler"
"time"
)

func main() {
asyncQueueSize := 10

applicationLogger := logger.NewAsyncLogger("example", time.DateTime, asyncQueueSize)

applicationFormatter := formatter.New("%(datetime) [%(level)] %(message)")
consoleHandler := handler.NewConsoleHandler(level.Debug, level.Null, applicationFormatter)
applicationLogger.AddHandler(consoleHandler)

for index := 0; index < asyncQueueSize; index++ {
applicationLogger.Warning("This message will be displayed.")
}

fmt.Println("This will be printed before the last warning log message.")

applicationLogger.WaitToFinishLogging()
}
2 changes: 1 addition & 1 deletion examples/customlogger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func main() {

applicationLogger.Debug("This message will not be displayed, because there are no handlers registered.")

applicationFormatter := formatter.New("%(isotime) [%(level)] %(message)")
applicationFormatter := formatter.New("%(datetime) [%(level)] %(message)")
consoleHandler := handler.NewConsoleHandler(level.Debug, level.Null, applicationFormatter)
applicationLogger.AddHandler(consoleHandler)

Expand Down
2 changes: 1 addition & 1 deletion examples/logtofile/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func main() {

applicationLogger := logger.New("file-logger", time.RFC3339)

applicationFormatter := formatter.New("%(isotime) [%(level)] %(message)")
applicationFormatter := formatter.New("%(datetime) [%(level)] %(message)")
fileHandler := handler.NewFileHandler(level.Warning, level.Null, applicationFormatter, fmt.Sprintf("%s/file.log", directory))
applicationLogger.AddHandler(fileHandler)

Expand Down
101 changes: 101 additions & 0 deletions pkg/logger/asynclogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package logger

import (
"github.com/dl1998/go-logging/pkg/common/level"
"github.com/dl1998/go-logging/pkg/logger/handler"
"github.com/dl1998/go-logging/pkg/logger/logrecord"
"sync"
)

// baseAsyncLogger struct contains basic fields for the async logger.
type baseAsyncLogger struct {
// baseLogger is a base logger.
*baseLogger
// messageQueue is a channel for the log messages.
messageQueue chan logrecord.Interface
// waitGroup is a wait group for the async logger messages.
waitGroup sync.WaitGroup
}

// startListeningMessages starts listening for messages in the messageQueue.
func (logger *baseAsyncLogger) startListeningMessages() {
for record := range logger.messageQueue {
for _, registeredHandler := range logger.handlers {
registeredHandler.Write(record)
}
logger.waitGroup.Done()
}
}

// WaitToFinishLogging waits for all messages to be logged.
func (logger *baseAsyncLogger) WaitToFinishLogging() {
logger.waitGroup.Wait()
}

// Open opens the messageQueue with the provided queueSize and starts listening
// for messages.
func (logger *baseAsyncLogger) Open(queueSize int) {
logger.messageQueue = make(chan logrecord.Interface, queueSize)
go logger.startListeningMessages()
}

// Close closes the messageQueue.
func (logger *baseAsyncLogger) Close() {
close(logger.messageQueue)
}

// Log logs interpolated message with the provided level.Level.
func (logger *baseAsyncLogger) Log(level level.Level, message string, parameters ...any) {
logger.waitGroup.Add(1)
record := logrecord.New(logger.name, level, logger.timeFormat, message, parameters, 3)
logger.messageQueue <- record
}

// AsyncLoggerInterface defines async logger interface.
type AsyncLoggerInterface interface {
Interface
WaitToFinishLogging()
Open(queueSize int)
Close()
}

// AsyncLogger represents an asynchronous logger.
type AsyncLogger struct {
// Logger is a standard logger.
*Logger
}

// NewAsyncLogger creates a new AsyncLogger with the provided name, timeFormat, and queueSize.
func NewAsyncLogger(name string, timeFormat string, queueSize int) *AsyncLogger {
newBaseLogger := &baseAsyncLogger{
baseLogger: &baseLogger{
name: name,
timeFormat: timeFormat,
handlers: make([]handler.Interface, 0),
},
messageQueue: make(chan logrecord.Interface, queueSize),
waitGroup: sync.WaitGroup{},
}
go newBaseLogger.startListeningMessages()
return &AsyncLogger{
Logger: &Logger{
baseLogger: newBaseLogger,
},
}
}

// WaitToFinishLogging waits for all messages to be logged.
func (logger *AsyncLogger) WaitToFinishLogging() {
logger.baseLogger.(*baseAsyncLogger).WaitToFinishLogging()
}

// Open opens the messageQueue with the provided queueSize and starts listening
// for messages.
func (logger *AsyncLogger) Open(queueSize int) {
logger.baseLogger.(*baseAsyncLogger).Open(queueSize)
}

// Close closes the messageQueue.
func (logger *AsyncLogger) Close() {
logger.baseLogger.(*baseAsyncLogger).Close()
}
Loading
Loading