/
log.go
88 lines (74 loc) · 2.32 KB
/
log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright (c) 2023 Migwi Ndung'u
// See LICENSE for details.
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/btcsuite/btclog"
"github.com/dmigwi/dhamana-protocol/client/sapphire"
"github.com/dmigwi/dhamana-protocol/client/server"
"github.com/dmigwi/dhamana-protocol/client/storage"
"github.com/dmigwi/dhamana-protocol/client/utils"
"github.com/jrick/logrotate/rotator"
)
const logFile = "dhamana.log"
var (
backendLog = btclog.NewBackend(logWriter{logFile})
// log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller
// requests it.
log = backendLog.Logger("MAIN")
serverLog = backendLog.Logger("SERVER")
sapphireLog = backendLog.Logger("SPPHRE")
storageLog = backendLog.Logger("STORE")
// logRotator is one of the logging outputs. It should be closed on
// application shutdown.
logRotators *rotator.Rotator
)
// Assigns the logger to use.
func init() {
server.UseLogger(serverLog)
sapphire.UseLogger(sapphireLog)
storage.UseLogger(storageLog)
}
// logWriter implements an io.Writer that outputs to both standard output and
// the write-end pipe of an initialized log rotator.
type logWriter struct {
loggerID string
}
// Write writes the data in p to standard out and the log rotator.
func (l logWriter) Write(p []byte) (n int, err error) {
os.Stdout.Write(p)
if logRotators == nil {
return 1, errors.New("log Rotator not initialised")
}
return logRotators.Write(p)
}
// setLogLevel the required log level.
func setLogLevel(level btclog.Level) {
log.SetLevel(level)
serverLog.SetLevel(level)
}
// shutdownLog safely triggers the log rotator shutdown.
func shutdownLog() {
if logRotators != nil {
logRotators.Close()
}
}
// initLogRotator initializes the logging rotater to write logs to logFile and
// create roll files in the same directory. It must be called before the
// package-global log rotater variables are used.
func initLogRotator(logDir string, maxRolls int) error {
err := os.MkdirAll(logDir, utils.FilePerm)
if err != nil {
return fmt.Errorf("failed to create log directory: %v", err)
}
r, err := rotator.New(filepath.Join(logDir, logFile), 32*1024, false, maxRolls)
if err != nil {
return fmt.Errorf("failed to create file rotator: %v", err)
}
logRotators = r
return nil
}