Compare commits

...

8 Commits
v1.0.2 ... main

Author SHA1 Message Date
kingecg 06f75dbe60 fix: 修复多个严重问题并改进代码质量
1. 修复空指针 panic 风险 - serveSignal() 添加 g.Running nil 检查
2. 修复错误未检查 - startDaemon/startTask 添加 cmd.Start() 错误处理
3. 修复 Task PID 未写入 - startTask() 现在正确写入 taskPidFile
4. 添加 PID 文件清理 - 进程退出时自动删除 PID 文件
5. 修复 goroutine 泄漏 - task 分支添加 signal.Stop()
6. 解耦日志依赖 - 移除 gologger,改为 Logger 接口
7. 添加单元测试 - godaemon_test.go 覆盖核心功能

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-11 09:31:25 +08:00
kingecg 6baf99cd11 docs: 添加详细代码注释和文档说明 2025-06-29 18:39:14 +08:00
kingecg 82a1a185d4 update deps 2025-06-29 17:33:45 +08:00
kingecg ec1d21254d "fix: 为信号通道添加缓冲区防止阻塞" 2025-06-29 17:29:28 +08:00
kingecg bd1ddd8020 chore: update module path to git.kingecg.top 2025-06-26 00:52:50 +08:00
kingecg 67ad586ae3 chore: update module path to git.kingecg.top 2025-06-25 23:39:24 +08:00
kingecg eff08899d1 chore: update module path to git.kingecg.top 2025-06-25 22:34:04 +08:00
kingecg 7b6c5fd331 chore: update module path to git.kingecg.top 2025-06-25 21:38:17 +08:00
14 changed files with 376 additions and 401 deletions

View File

@ -11,8 +11,8 @@ Usage:
import (
"time"
"git.pyer.club/kingecg/godaemon"
"git.pyer.club/kingecg/gologger"
"git.kingecg.top/kingecg/godaemon"
"git.kingecg.top/kingecg/gologger"
)
var daemon *godaemon.GoDaemon

4
go.mod
View File

@ -1,5 +1,5 @@
module git.pyer.club/kingecg/godaemon
module git.kingecg.top/kingecg/godaemon
go 1.19
require git.pyer.club/kingecg/gologger v1.0.4 // indirect
require git.kingecg.top/kingecg/gologger v1.0.10

6
go.sum
View File

@ -1,4 +1,2 @@
git.pyer.club/kingecg/gologger v1.0.1 h1:snCb0ePlfDUglX+CHwNzq5MRK5uNTnPUks1Dnapl/p8=
git.pyer.club/kingecg/gologger v1.0.1/go.mod h1:SNSl2jRHPzIpHSzdKOoVG798rtYMjPDPFyxUrEgivkY=
git.pyer.club/kingecg/gologger v1.0.4 h1:uSStqVw1H1hPTbRiIhRBOxHMw/tRWMZEvsspIKnNpGk=
git.pyer.club/kingecg/gologger v1.0.4/go.mod h1:SNSl2jRHPzIpHSzdKOoVG798rtYMjPDPFyxUrEgivkY=
git.kingecg.top/kingecg/gologger v1.0.10 h1:o6CNJ3TM9wOnKsV0hNasSSmZXEOMl5mBXZDnKJnC0a0=
git.kingecg.top/kingecg/gologger v1.0.10/go.mod h1:auMA7VGipqttnF0jmtclhbaIr08gqtVPj6BSMknHTOE=

View File

@ -1,3 +1,5 @@
// Package godaemon provides a simple daemon library for Go applications.
// It allows applications to run as daemon processes with start/stop/restart capabilities.
package godaemon
import (
@ -10,47 +12,82 @@ import (
"strconv"
"strings"
"syscall"
"git.pyer.club/kingecg/gologger"
)
const (
daemon_env_key = "_go_daemon"
daemon_process = "g_daemon"
daemon_task = "g_dtask"
daemon_taskargs = "g_args"
)
type GoDaemon struct {
pidFile string
taskPidFile string
flag *string
sigChan chan os.Signal
state string
*gologger.Logger
Running *exec.Cmd
StartFn func(*GoDaemon)
StopFn func(*GoDaemon)
// Logger defines the logging interface used by GoDaemon
type Logger interface {
Debug(v ...any)
Info(v ...any)
Error(v ...any)
}
// defaultLogger is a simple logger that uses fmt.Println
type defaultLogger struct{}
func (d *defaultLogger) Debug(v ...any) { fmt.Println(v...) }
func (d *defaultLogger) Info(v ...any) { fmt.Println(v...) }
func (d *defaultLogger) Error(v ...any) { fmt.Print("[ERROR] "); fmt.Println(v...) }
// Constants defining environment variable keys and values used for process identification
const (
daemon_env_key = "_go_daemon" // Environment variable key for process role identification
daemon_process = "g_daemon" // Value indicating daemon process role
daemon_task = "g_dtask" // Value indicating task process role
daemon_taskargs = "g_args" // Environment variable key for storing task arguments
)
// GoDaemon represents a daemon process manager
type GoDaemon struct {
pidFile string // Path to file storing daemon process PID
taskPidFile string // Path to file storing task process PID
flag *string // Command line flag for signal control
sigChan chan os.Signal // Channel for receiving OS signals
state string // Current state of the daemon ("running", "stopped", etc.)
logger Logger // Logger for logging
Running *exec.Cmd // Currently running task process
StartFn func(*GoDaemon) // Function called when task starts
StopFn func(*GoDaemon) // Function called when task stops
}
// GetPid retrieves the daemon process ID from the PID file
//
// Returns:
// - int: process ID if found and valid, 0 otherwise
func (g *GoDaemon) GetPid() int {
pids, ferr := os.ReadFile(g.pidFile)
pid, err := strconv.Atoi(string(pids))
if err != nil || ferr != nil {
if ferr != nil {
return 0
}
return pid
}
func (g *GoDaemon) GetTaskPid() int {
pids, ferr := os.ReadFile(g.taskPidFile)
pid, err := strconv.Atoi(string(pids))
if err != nil || ferr != nil {
pid, err := strconv.Atoi(strings.TrimSpace(string(pids)))
if err != nil {
return 0
}
return pid
}
// GetTaskPid retrieves the task process ID from the task PID file
//
// Returns:
// - int: process ID if found and valid, 0 otherwise
func (g *GoDaemon) GetTaskPid() int {
pids, ferr := os.ReadFile(g.taskPidFile)
if ferr != nil {
return 0
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pids)))
if err != nil {
return 0
}
return pid
}
// Start begins the daemon process management based on the current process role
//
// Behavior depends on process role:
// - Master: starts the daemon process or sends signals to running daemon
// - Daemon: manages task process lifecycle
// - Task: executes the user-provided StartFn
func (g *GoDaemon) Start() {
if g.flag == nil {
g.flag = flag.String("s", "", "send signal to daemon. support: reload and quit")
@ -78,39 +115,46 @@ func (g *GoDaemon) Start() {
fmt.Println("Daemon process not found")
return
}
g.Debug("Send signal:", p.Pid, sig)
g.logger.Debug("Send signal:", p.Pid, sig)
p.Signal(sig)
} else if IsDaemon() {
pid := os.Getpid()
os.WriteFile(g.pidFile, []byte(strconv.Itoa(pid)), 0644)
g.sigChan = make(chan os.Signal)
g.sigChan = make(chan os.Signal, 1)
signal.Notify(g.sigChan, syscall.SIGTERM, syscall.SIGHUP)
go g.serveSignal()
for {
g.Debug("Starting new task")
g.logger.Debug("Starting new task")
g.Running = g.startTask()
g.state = "running"
g.Running.Process.Wait()
if g.state == "stopped" {
g.Debug("daemon is stopped, exit now")
g.logger.Debug("daemon is stopped, exit now")
break
}
}
} else {
waiter := make(chan os.Signal, 1)
signal.Notify(waiter, syscall.SIGTERM, syscall.SIGHUP)
g.StartFn(g)
g.Info("daemon task is started")
g.logger.Info("daemon task is started")
<-waiter
g.Info("daemon task will be stopped")
g.logger.Info("daemon task will be stopped")
signal.Stop(waiter)
g.StopFn(g)
}
}
// serveSignal handles incoming OS signals for the daemon process
//
// Signals handled:
// - SIGTERM: stops the daemon
// - SIGHUP: restarts the task process
func (g *GoDaemon) serveSignal() {
sig := <-g.sigChan
if sig == syscall.SIGTERM {
@ -119,9 +163,27 @@ func (g *GoDaemon) serveSignal() {
g.state = "restart"
}
g.Running.Process.Signal(syscall.SIGTERM)
if g.Running != nil && g.Running.Process != nil {
g.Running.Process.Signal(syscall.SIGTERM)
// Wait for task to exit after sending SIGTERM
g.Running.Wait()
}
// Cleanup PID files when daemon stops
if g.state == "stopped" {
g.cleanupPIDFiles()
}
}
// cleanupPIDFiles removes the PID files on daemon exit
func (g *GoDaemon) cleanupPIDFiles() {
os.Remove(g.pidFile)
os.Remove(g.taskPidFile)
}
// getDaemonProcess retrieves the daemon process instance if it's running
//
// Returns:
// - *os.Process: running daemon process if found, nil otherwise
func (g *GoDaemon) getDaemonProcess() *os.Process {
pid := g.GetPid()
if pid == 0 {
@ -129,7 +191,7 @@ func (g *GoDaemon) getDaemonProcess() *os.Process {
}
p, err := os.FindProcess(pid)
if err != nil {
g.Debug(err)
g.logger.Debug(err)
}
serr := p.Signal(syscall.Signal(0))
if serr != nil {
@ -138,6 +200,9 @@ func (g *GoDaemon) getDaemonProcess() *os.Process {
return p
}
// startDaemon starts a new daemon process in the background
//
// Checks if daemon is already running before starting a new instance
func (g *GoDaemon) startDaemon() {
dp := g.getDaemonProcess()
@ -151,9 +216,17 @@ func (g *GoDaemon) startDaemon() {
cmd.Env = append(cmd.Env, daemon_env_key+"="+daemon_process)
pargs := os.Args[1:]
cmd.Env = append(cmd.Env, daemon_taskargs+"="+strings.Join(pargs, ";"))
cmd.Start()
if err := cmd.Start(); err != nil {
g.logger.Error("failed to start daemon:", err)
return
}
fmt.Println("daemon started with pid:", cmd.Process.Pid)
}
// startTask starts a new task process with the configured arguments
//
// Returns:
// - *exec.Cmd: the started command representing the task process
func (g *GoDaemon) startTask() *exec.Cmd {
extraArgs, _ := os.LookupEnv(daemon_taskargs)
var cmd *exec.Cmd
@ -167,27 +240,66 @@ func (g *GoDaemon) startTask() *exec.Cmd {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(cmd.Env, daemon_env_key+"="+daemon_task)
cmd.Start()
if err := cmd.Start(); err != nil {
g.logger.Error("failed to start task:", err)
return nil
}
// Write task PID to file
os.WriteFile(g.taskPidFile, []byte(strconv.Itoa(cmd.Process.Pid)), 0644)
return cmd
}
// IsMaster checks if the current process is the master process
//
// Returns:
// - bool: true if this is the master process, false otherwise
func IsMaster() bool {
goDaemonEnv, _ := os.LookupEnv(daemon_env_key)
return goDaemonEnv == ""
}
// IsDaemon checks if the current process is the daemon process
//
// Returns:
// - bool: true if this is the daemon process, false otherwise
func IsDaemon() bool {
goDaemonEnv, _ := os.LookupEnv(daemon_env_key)
return goDaemonEnv == daemon_process
}
// IsDaemonTask checks if the current process is the task process
//
// Returns:
// - bool: true if this is the task process, false otherwise
func IsDaemonTask() bool {
goDaemonEnv, _ := os.LookupEnv(daemon_env_key)
return goDaemonEnv == daemon_task
}
// NewGoDaemon creates a new GoDaemon instance
//
// Parameters:
// - start: function to be called when the task process starts
// - stop: function to be called when the task process stops
//
// Returns:
// - *GoDaemon: initialized GoDaemon instance
func NewGoDaemon(start, stop func(*GoDaemon)) *GoDaemon {
return NewGoDaemonWithLogger(start, stop, &defaultLogger{})
}
// NewGoDaemonWithLogger creates a new GoDaemon instance with a custom logger
//
// Parameters:
// - start: function to be called when the task process starts
// - stop: function to be called when the task process stops
// - logger: custom logger implementation
//
// Returns:
// - *GoDaemon: initialized GoDaemon instance
func NewGoDaemonWithLogger(start, stop func(*GoDaemon), logger Logger) *GoDaemon {
godaemon := &GoDaemon{
Logger: gologger.GetLogger("daemon"),
logger: logger,
}
execName, _ := os.Executable()

215
godaemon_test.go Normal file
View File

@ -0,0 +1,215 @@
package godaemon
import (
"os"
"path/filepath"
"testing"
)
// mockLogger is a simple mock logger for testing
type mockLogger struct {
debugLogs []any
infoLogs []any
errorLogs []any
}
func (m *mockLogger) Debug(v ...any) { m.debugLogs = append(m.debugLogs, v) }
func (m *mockLogger) Info(v ...any) { m.infoLogs = append(m.infoLogs, v) }
func (m *mockLogger) Error(v ...any) { m.errorLogs = append(m.errorLogs, v) }
func TestIsMaster(t *testing.T) {
// Clear the environment variable first
os.Unsetenv(daemon_env_key)
if !IsMaster() {
t.Error("IsMaster() should return true when environment variable is not set")
}
}
func TestIsDaemon(t *testing.T) {
tests := []struct {
name string
envValue string
expected bool
}{
{"daemon process", daemon_process, true},
{"task process", daemon_task, false},
{"empty", "", false},
{"unknown value", "unknown", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.envValue == "" {
os.Unsetenv(daemon_env_key)
} else {
os.Setenv(daemon_env_key, tt.envValue)
}
defer os.Unsetenv(daemon_env_key)
if got := IsDaemon(); got != tt.expected {
t.Errorf("IsDaemon() = %v, want %v", got, tt.expected)
}
})
}
}
func TestIsDaemonTask(t *testing.T) {
tests := []struct {
name string
envValue string
expected bool
}{
{"task process", daemon_task, true},
{"daemon process", daemon_process, false},
{"empty", "", false},
{"unknown value", "unknown", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.envValue == "" {
os.Unsetenv(daemon_env_key)
} else {
os.Setenv(daemon_env_key, tt.envValue)
}
defer os.Unsetenv(daemon_env_key)
if got := IsDaemonTask(); got != tt.expected {
t.Errorf("IsDaemonTask() = %v, want %v", got, tt.expected)
}
})
}
}
func TestNewGoDaemon(t *testing.T) {
logger := &mockLogger{}
startCalled := false
stopCalled := false
startFn := func(g *GoDaemon) { startCalled = true }
stopFn := func(g *GoDaemon) { stopCalled = true }
gd := NewGoDaemonWithLogger(startFn, stopFn, logger)
if gd == nil {
t.Fatal("NewGoDaemonWithLogger returned nil")
}
if gd.StartFn == nil || gd.StopFn == nil {
t.Error("StartFn or StopFn is nil")
}
if gd.logger == nil {
t.Error("logger is nil")
}
if gd.pidFile == "" || gd.taskPidFile == "" {
t.Error("PID file paths are not set")
}
// Verify functions are properly assigned
gd.StartFn(gd)
if !startCalled {
t.Error("StartFn was not called")
}
gd.StopFn(gd)
if !stopCalled {
t.Error("StopFn was not called")
}
}
func TestGetPid(t *testing.T) {
tmpDir := t.TempDir()
pidFile := filepath.Join(tmpDir, "test.pid")
gd := &GoDaemon{pidFile: pidFile}
// Test when file doesn't exist
if got := gd.GetPid(); got != 0 {
t.Errorf("GetPid() = %v, want 0 when file doesn't exist", got)
}
// Test with invalid content
os.WriteFile(pidFile, []byte("invalid"), 0644)
if got := gd.GetPid(); got != 0 {
t.Errorf("GetPid() = %v, want 0 for invalid content", got)
}
// Test with valid PID
os.WriteFile(pidFile, []byte("12345"), 0644)
if got := gd.GetPid(); got != 12345 {
t.Errorf("GetPid() = %v, want 12345", got)
}
// Test with whitespace
os.WriteFile(pidFile, []byte(" 67890 \n"), 0644)
if got := gd.GetPid(); got != 67890 {
t.Errorf("GetPid() = %v, want 67890 with whitespace", got)
}
}
func TestGetTaskPid(t *testing.T) {
tmpDir := t.TempDir()
taskPidFile := filepath.Join(tmpDir, "test.task.pid")
gd := &GoDaemon{taskPidFile: taskPidFile}
// Test when file doesn't exist
if got := gd.GetTaskPid(); got != 0 {
t.Errorf("GetTaskPid() = %v, want 0 when file doesn't exist", got)
}
// Test with valid PID
os.WriteFile(taskPidFile, []byte("54321"), 0644)
if got := gd.GetTaskPid(); got != 54321 {
t.Errorf("GetTaskPid() = %v, want 54321", got)
}
}
func TestCleanupPIDFiles(t *testing.T) {
tmpDir := t.TempDir()
pidFile := filepath.Join(tmpDir, "test.pid")
taskPidFile := filepath.Join(tmpDir, "test.task.pid")
gd := &GoDaemon{pidFile: pidFile, taskPidFile: taskPidFile}
// Create PID files
os.WriteFile(pidFile, []byte("12345"), 0644)
os.WriteFile(taskPidFile, []byte("67890"), 0644)
// Verify files exist
if _, err := os.Stat(pidFile); os.IsNotExist(err) {
t.Error("pidFile should exist before cleanup")
}
if _, err := os.Stat(taskPidFile); os.IsNotExist(err) {
t.Error("taskPidFile should exist before cleanup")
}
// Cleanup
gd.cleanupPIDFiles()
// Verify files are removed
if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
t.Error("pidFile should be removed after cleanup")
}
if _, err := os.Stat(taskPidFile); !os.IsNotExist(err) {
t.Error("taskPidFile should be removed after cleanup")
}
}
func TestDefaultLogger(t *testing.T) {
logger := &defaultLogger{}
// These should not panic
logger.Debug("debug", "message", 123)
logger.Info("info", "message")
logger.Error("error", "message")
}
func TestLoggerInterface(t *testing.T) {
// Verify that defaultLogger implements Logger interface
var _ Logger = &defaultLogger{}
var _ Logger = &mockLogger{}
}

BIN
test/main

Binary file not shown.

View File

@ -3,8 +3,8 @@ package main
import (
"time"
"git.pyer.club/kingecg/godaemon"
"git.pyer.club/kingecg/gologger"
"git.kingecg.top/kingecg/godaemon"
"git.kingecg.top/kingecg/gologger"
)
var daemon *godaemon.GoDaemon

View File

@ -1,18 +0,0 @@
# ---> Go
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
log/

View File

@ -1,3 +0,0 @@
# gologger
a logger used in go

View File

@ -1,49 +0,0 @@
package gologger
import (
"fmt"
)
const (
ErrorTemplate = "\033[1;31m%s\033[0m"
WarnTemplate = "\033[1;33m%s\033[0m"
InfoTemplate = "\033[1;32m%s\033[0m"
DebugTemplate = "\033[1;34m%s\033[0m"
TraceTemplate = "\033[1;35m%s\033[0m"
)
type ConsoleAppender struct {
}
// Close implements LoggerAppender.
func (c *ConsoleAppender) Close() {
}
func (c *ConsoleAppender) GetName() string {
return "console"
}
func (c *ConsoleAppender) Append(logEvent LogEvent) {
logMsg := format(logEvent)
switch logEvent.Level {
case Error:
fmt.Printf(ErrorTemplate, logMsg)
case Warn:
fmt.Printf(WarnTemplate, logMsg)
case Info:
fmt.Printf(InfoTemplate, logMsg)
case Debug:
fmt.Printf(DebugTemplate, logMsg)
case Trace:
fmt.Printf(TraceTemplate, logMsg)
}
}
func makeConsoleAppender(appenderConfig LogAppenderConfig) *LoggerAppender {
var appender LoggerAppender = &ConsoleAppender{}
return &appender
}
func init() {
RegistAppender("console", makeConsoleAppender)
}

View File

@ -1,74 +0,0 @@
package gologger
import (
"os"
"path/filepath"
)
type FileAppender struct {
filePath string
lchan chan LogEvent
file *os.File
stopChan chan struct{}
}
// Close implements LoggerAppender.
func (f *FileAppender) Close() {
//send stop signal
f.stopChan <- struct{}{}
}
func (f *FileAppender) GetName() string {
return "FileAppender:" + f.filePath
}
func (f *FileAppender) start() {
f.lchan = make(chan LogEvent, 10)
f.stopChan = make(chan struct{})
if f.file == nil || int(f.file.Fd()) == -1 {
dirName := filepath.Dir(f.filePath)
_, err := os.Stat(dirName)
if err != nil && os.IsNotExist(err) {
os.MkdirAll(dirName, 0755)
}
f.file, _ = os.OpenFile(f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
}
go func() {
defer f.file.Close()
for {
select {
case <-f.stopChan:
return
case logEvent := <-f.lchan:
logMsg := format(logEvent)
f.file.WriteString(logMsg)
}
}
}()
}
func (f *FileAppender) Append(logEvent LogEvent) {
f.lchan <- logEvent
}
func makeFileAppender(appenderConfig LogAppenderConfig) *LoggerAppender {
var logfile interface{}
var ok bool
logfile, ok = appenderConfig.Options["file"]
if !ok {
logfile = "default.log"
}
var ret LoggerAppender = &FileAppender{
filePath: logfile.(string),
}
ret.(*FileAppender).start()
return &ret
}
func init() {
RegistAppender("file", makeFileAppender)
}

View File

@ -1,53 +0,0 @@
package gologger
import (
"fmt"
"strings"
)
const logTemplate = "[%s] %s : %s - %s\n"
func format(logEvent LogEvent) string {
data := logEvent.Ts.Format("2006-01-02 15:04:05")
msg := ""
firstMsg := logEvent.Data[0]
if isFormatString(firstMsg) {
msg = fmt.Sprintf(firstMsg.(string), logEvent.Data[1:]...)
} else {
msg = sprint(logEvent.Data)
}
ret := fmt.Sprintf(logTemplate, data, logEvent.Category, getLogLevelStr(logEvent.Level), msg)
return ret
}
func getLogLevelStr(level int) string {
for name, slevel := range logLevelMap {
if slevel == level {
return strings.ToUpper(name)
}
}
return "Unknown"
}
func isFormatString(f interface{}) bool {
s, ok := f.(string)
if !ok {
return false
}
// 尝试使用空接口来格式化字符串
m := fmt.Sprintf(s, []interface{}{}...)
return strings.Index(m, "MISSING") != -1
}
func sprint(s []interface{}) string {
str := make([]any, len(s))
for i, v := range s {
if i > 0 {
str[i] = fmt.Sprintf(" %v", v)
} else {
str[i] = fmt.Sprintf("%v", v)
}
}
return fmt.Sprint(str...)
}

View File

@ -1,153 +0,0 @@
package gologger
import (
"strings"
"time"
)
const (
NoLog = iota
Error
Warn
Info
Debug
Trace
)
var logLevelMap map[string]int = map[string]int{
"off": NoLog,
"error": Error,
"warn": Warn,
"info": Info,
"debug": Debug,
"trace": Trace,
}
var loggerMap map[string]*Logger = map[string]*Logger{}
var appenderFactoryMap map[string]func(LogAppenderConfig) *LoggerAppender = map[string]func(LogAppenderConfig) *LoggerAppender{}
var appenders map[string]*LoggerAppender = map[string]*LoggerAppender{}
var loggerConfig LoggersConfig
type LogAppenderConfig struct {
Type string `json:"type"`
Options map[string]interface{} `json:"options"`
}
type LogConfig struct {
Level string `json:"level"`
Appenders []string `json:"appenders"`
}
type LoggersConfig struct {
Appenders map[string]LogAppenderConfig `json:"appenders"`
Categories map[string]LogConfig `json:"categories"`
}
type Logger struct {
category string
level int
appenders []*LoggerAppender
}
type LogEvent struct {
Category string
Ts time.Time
Level int
Data []interface{}
}
type LoggerAppender interface {
GetName() string
Append(logEvent LogEvent)
Close()
}
var consoleAppender LoggerAppender = &ConsoleAppender{}
var defaultLogger = &Logger{
level: Error,
appenders: []*LoggerAppender{&consoleAppender},
}
func (l *Logger) log(Level int, msg []interface{}) {
if Level <= l.level {
now := time.Now()
logEvent := LogEvent{l.category, now, Level, msg}
for _, appender := range l.appenders {
(*appender).Append(logEvent)
}
// l.Appender.Append(logEvent)
// fmt.Println(now.Format("2006-01-02 15:04:05"), " ", l.Name, ": ", msg)
}
}
func (l *Logger) Error(msg ...interface{}) {
l.log(Error, msg)
}
func (l *Logger) Warn(msg ...interface{}) {
l.log(Warn, msg)
}
func (l *Logger) Info(msg ...interface{}) {
l.log(Info, msg)
}
func (l *Logger) Debug(msg ...interface{}) {
l.log(Debug, msg)
}
func (l *Logger) Trace(msg ...interface{}) {
l.log(Trace, msg)
}
func GetLogger(name string) *Logger {
if logger, ok := loggerMap[name]; ok {
return logger
} else {
logConfig, ok := loggerConfig.Categories[name]
if ok {
return makeLogger(name, logConfig)
}
if name == "default" {
return defaultLogger
}
l := *GetLogger("default")
l.category = name
loggerMap[name] = &l
return &l
}
}
func makeLogger(name string, config LogConfig) *Logger {
logger := &Logger{category: name}
levelstr := strings.ToLower(config.Level)
logger.level = logLevelMap[levelstr]
if config.Appenders == nil || len(config.Appenders) == 0 {
logger.appenders = []*LoggerAppender{&consoleAppender}
} else {
logger.appenders = make([]*LoggerAppender, len(config.Appenders))
for i, appenderName := range config.Appenders {
logger.appenders[i] = appenders[appenderName]
}
}
loggerMap[name] = logger
return logger
}
func Configure(config LoggersConfig) {
loggerConfig = config
for name, appenderConfig := range loggerConfig.Appenders {
appenderFactory, ok := appenderFactoryMap[appenderConfig.Type]
if ok {
appenders[name] = appenderFactory(appenderConfig)
} else {
appenders[name] = &consoleAppender
}
}
for name, _ := range loggerConfig.Categories {
GetLogger(name)
}
}
func RegistAppender(typeName string, appenderCreatCb func(LogAppenderConfig) *LoggerAppender) {
appenderFactoryMap[typeName] = appenderCreatCb
}

4
vendor/modules.txt vendored
View File

@ -1,3 +1,3 @@
# git.pyer.club/kingecg/gologger v1.0.4
# git.kingecg.top/kingecg/gologger v1.0.10
## explicit; go 1.19
git.pyer.club/kingecg/gologger
git.kingecg.top/kingecg/gologger