summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2021-09-28 21:11:50 +0300
committerPaul Buetow <paul@buetow.org>2021-10-02 12:26:36 +0300
commit609921f9c783941eaa9019a92b78ec45b49d681c (patch)
treec4fc6b20404d0f922dc2825e4624be8c04479cbf
parentfcaa94c7453efa0d74e330128c0f5c2cde8f11b3 (diff)
can have daily and normal file log rotation
-rw-r--r--cmd/dserver/main.go1
-rw-r--r--internal/config/args.go43
-rw-r--r--internal/config/config.go43
-rw-r--r--internal/config/setup.go4
-rw-r--r--internal/io/dlog/dlog.go14
-rw-r--r--internal/io/dlog/loggers/factory.go8
-rw-r--r--internal/io/dlog/loggers/file.go117
-rw-r--r--internal/io/dlog/loggers/fout.go4
-rw-r--r--internal/io/dlog/strategy.go22
-rw-r--r--internal/io/logger/logger.go443
-rw-r--r--internal/io/logger/modes.go13
-rw-r--r--internal/io/logger/strategy.go22
12 files changed, 123 insertions, 611 deletions
diff --git a/cmd/dserver/main.go b/cmd/dserver/main.go
index a3add5b..e77bc21 100644
--- a/cmd/dserver/main.go
+++ b/cmd/dserver/main.go
@@ -39,7 +39,6 @@ func main() {
flag.StringVar(&args.ConfigFile, "cfg", "", "Config file path")
flag.StringVar(&args.LogDir, "logDir", "", "Log dir")
flag.StringVar(&args.LogLevel, "logLevel", "", "Log level")
- flag.StringVar(&args.LogDir, "logDir", "", "Log dir path")
flag.Parse()
args.NoColor = !color
diff --git a/internal/config/args.go b/internal/config/args.go
index 767cc65..7f24348 100644
--- a/internal/config/args.go
+++ b/internal/config/args.go
@@ -1,7 +1,6 @@
package config
import (
- "flag"
"fmt"
"strings"
@@ -68,48 +67,6 @@ func (a *Args) String() string {
return sb.String()
}
-// Based on the argument list, transform/manipulate some of the arguments.
-func (a *Args) transformConfig(args []string, client *ClientConfig, server *ServerConfig, common *CommonConfig) (*ClientConfig, *ServerConfig, *CommonConfig) {
- if a.LogDir != "" {
- common.LogDir = a.LogDir
- if common.LogStrategy == "" {
- // TODO: Implement the other (not-daily) log strategy for the server.
- common.LogStrategy = "daily"
- }
- }
-
- if a.LogLevel != "" {
- common.LogLevel = a.LogLevel
- }
-
- if a.SSHPort != DefaultSSHPort {
- common.SSHPort = a.SSHPort
- }
- if a.NoColor {
- client.TermColorsEnable = false
- }
-
- if a.Spartan {
- a.Quiet = true
- a.NoColor = true
- }
-
- if a.Discovery == "" && a.ServersStr == "" {
- a.Serverless = true
- }
-
- // Interpret additional args as file list.
- if a.What == "" {
- var files []string
- for _, file := range flag.Args() {
- files = append(files, file)
- }
- a.What = strings.Join(files, ",")
- }
-
- return client, server, common
-}
-
// SerializeOptions returns a string ready to be sent over the wire to the server.
func (a *Args) SerializeOptions() string {
return fmt.Sprintf("quiet=%v:spartan=%v", a.Quiet, a.Spartan)
diff --git a/internal/config/config.go b/internal/config/config.go
index c9f411c..76dcc65 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -2,6 +2,7 @@ package config
import (
"encoding/json"
+ "flag"
"fmt"
"io/ioutil"
"os"
@@ -78,3 +79,45 @@ func (c *configInitializer) parseSpecificConfig(configFile string) {
panic(fmt.Sprintf("Unable to parse config file %s: %v", configFile, err))
}
}
+
+func (c *configInitializer) transformConfig(args *Args, additionalArgs []string,
+ client *ClientConfig, server *ServerConfig, common *CommonConfig) (*ClientConfig, *ServerConfig, *CommonConfig) {
+ if args.LogDir != "" {
+ common.LogDir = args.LogDir
+ if common.LogStrategy == "" {
+ // TODO: Implement the other (not-daily) log strategy for the server.
+ common.LogStrategy = "daily"
+ }
+ }
+
+ if args.LogLevel != "" {
+ common.LogLevel = args.LogLevel
+ }
+
+ if args.SSHPort != DefaultSSHPort {
+ common.SSHPort = args.SSHPort
+ }
+ if args.NoColor {
+ client.TermColorsEnable = false
+ }
+
+ if args.Spartan {
+ args.Quiet = true
+ args.NoColor = true
+ }
+
+ if args.Discovery == "" && args.ServersStr == "" {
+ args.Serverless = true
+ }
+
+ // Interpret additional args as file list.
+ if args.What == "" {
+ var files []string
+ for _, file := range flag.Args() {
+ files = append(files, file)
+ }
+ args.What = strings.Join(files, ",")
+ }
+
+ return client, server, common
+}
diff --git a/internal/config/setup.go b/internal/config/setup.go
index be8e867..7800914 100644
--- a/internal/config/setup.go
+++ b/internal/config/setup.go
@@ -8,8 +8,8 @@ func Setup(args *Args, additionalArgs []string) {
Client: newDefaultClientConfig(),
}
initializer.parseConfig(args)
- Client, Server, Common = args.transformConfig(
- additionalArgs,
+ Client, Server, Common = initializer.transformConfig(
+ args, additionalArgs,
initializer.Client,
initializer.Server,
initializer.Common,
diff --git a/internal/io/dlog/dlog.go b/internal/io/dlog/dlog.go
index 49b405d..49533a5 100644
--- a/internal/io/dlog/dlog.go
+++ b/internal/io/dlog/dlog.go
@@ -36,19 +36,21 @@ func Start(ctx context.Context, wg *sync.WaitGroup, sourceProcess source, logLev
Common.FatalPanic("Logger already started")
}
+ strategy := loggers.GetStrategy(config.Common.LogStrategy)
level := newLevel(logLevel)
+
switch sourceProcess {
case CLIENT:
// This is a DTail client process running.
impl := loggers.FOUT
- Client = New(CLIENT, CLIENT, impl, level)
- Server = New(CLIENT, SERVER, impl, level)
+ Client = New(CLIENT, CLIENT, level, impl, strategy)
+ Server = New(CLIENT, SERVER, level, impl, strategy)
Common = Client
case SERVER:
// This is a DTail server process running.
impl := loggers.FILE
- Client = New(SERVER, CLIENT, impl, level)
- Server = New(SERVER, SERVER, impl, level)
+ Client = New(SERVER, CLIENT, level, impl, strategy)
+ Server = New(SERVER, SERVER, level, impl, strategy)
Common = Server
}
@@ -80,13 +82,13 @@ type DLog struct {
}
// New creates a new DTail logger.
-func New(sourceProcess, sourcePackage source, impl loggers.Impl, maxLevel level) *DLog {
+func New(sourceProcess, sourcePackage source, maxLevel level, impl loggers.Impl, strategy loggers.Strategy) *DLog {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
return &DLog{
- logger: loggers.Factory(sourceProcess.String(), impl),
+ logger: loggers.Factory(sourceProcess.String(), impl, strategy),
sourceProcess: sourceProcess,
sourcePackage: sourcePackage,
maxLevel: maxLevel,
diff --git a/internal/io/dlog/loggers/factory.go b/internal/io/dlog/loggers/factory.go
index 3eb29c5..8697dc4 100644
--- a/internal/io/dlog/loggers/factory.go
+++ b/internal/io/dlog/loggers/factory.go
@@ -17,11 +17,11 @@ const (
var factoryMap map[string]Logger
var factoryMutex sync.Mutex
-func Factory(name string, impl Impl) Logger {
+func Factory(name string, impl Impl, strategy Strategy) Logger {
factoryMutex.Lock()
defer factoryMutex.Unlock()
- id := fmt.Sprintf("name:%s,impl:%v", name, impl)
+ id := fmt.Sprintf("name:%s,fileBase:%s,impl:%v", name, strategy.FileBase, impl)
if factoryMap == nil {
factoryMap = make(map[string]Logger)
@@ -36,10 +36,10 @@ func Factory(name string, impl Impl) Logger {
singleton = newStdout()
factoryMap[id] = singleton
case FILE:
- singleton = newFile()
+ singleton = newFile(strategy)
factoryMap[id] = singleton
case FOUT:
- singleton = newFout()
+ singleton = newFout(strategy)
factoryMap[id] = singleton
}
}
diff --git a/internal/io/dlog/loggers/file.go b/internal/io/dlog/loggers/file.go
index 1c525c9..dcdd7d0 100644
--- a/internal/io/dlog/loggers/file.go
+++ b/internal/io/dlog/loggers/file.go
@@ -12,49 +12,54 @@ import (
"github.com/mimecast/dtail/internal/config"
)
+type fileWriter struct {
+}
+
type fileMessageBuf struct {
now time.Time
message string
}
type file struct {
- bufferCh chan *fileMessageBuf
- pauseCh chan struct{}
- resumeCh chan struct{}
- rotateCh chan struct{}
- flushCh chan struct{}
- lastDateStr string
- fd *os.File
- writer *bufio.Writer
- mutex sync.Mutex
- started bool
+ bufferCh chan *fileMessageBuf
+ pauseCh chan struct{}
+ resumeCh chan struct{}
+ rotateCh chan struct{}
+ flushCh chan struct{}
+ fd *os.File
+ writer *bufio.Writer
+ mutex sync.Mutex
+ started bool
+ lastFileName string
+ strategy Strategy
}
-func newFile() *file {
+func newFile(strategy Strategy) *file {
f := file{
bufferCh: make(chan *fileMessageBuf, runtime.NumCPU()*100),
pauseCh: make(chan struct{}),
resumeCh: make(chan struct{}),
rotateCh: make(chan struct{}),
flushCh: make(chan struct{}),
+ strategy: strategy,
}
- f.getWriter(time.Now().Format("20060102"))
+
return &f
}
-func (s *file) Start(ctx context.Context, wg *sync.WaitGroup) {
- s.mutex.Lock()
- defer s.mutex.Unlock()
+func (f *file) Start(ctx context.Context, wg *sync.WaitGroup) {
+ f.mutex.Lock()
+ defer f.mutex.Unlock()
// Logger already started from another Goroutine.
- if s.started {
+ if f.started {
wg.Done()
return
}
pause := func(ctx context.Context) {
select {
- case <-s.resumeCh:
+ case <-f.resumeCh:
return
case <-ctx.Done():
return
@@ -66,55 +71,61 @@ func (s *file) Start(ctx context.Context, wg *sync.WaitGroup) {
for {
select {
- case m := <-s.bufferCh:
- s.write(m)
- case <-s.pauseCh:
+ case m := <-f.bufferCh:
+ f.write(m)
+ case <-f.pauseCh:
pause(ctx)
- case <-s.flushCh:
- s.flush()
+ case <-f.flushCh:
+ f.flush()
case <-ctx.Done():
- s.flush()
- s.fd.Close()
+ f.flush()
+ f.fd.Close()
return
}
}
}()
- s.started = true
+ f.started = true
}
-func (s *file) Log(now time.Time, message string) {
- s.bufferCh <- &fileMessageBuf{now, message}
+func (f *file) Log(now time.Time, message string) {
+ f.bufferCh <- &fileMessageBuf{now, message}
}
-func (s *file) LogWithColors(now time.Time, message, coloredMessage string) {
+func (f *file) LogWithColors(now time.Time, message, coloredMessage string) {
panic("Colors not supported in file logger")
}
-func (s *file) Pause() { s.pauseCh <- struct{}{} }
-func (s *file) Resume() { s.resumeCh <- struct{}{} }
-func (s *file) Flush() { s.flushCh <- struct{}{} }
+func (f *file) Pause() { f.pauseCh <- struct{}{} }
+func (f *file) Resume() { f.resumeCh <- struct{}{} }
+func (f *file) Flush() { f.flushCh <- struct{}{} }
// TODO: Test that Rotate() actually works.
-func (s *file) Rotate() { s.rotateCh <- struct{}{} }
-func (file) SupportsColors() bool { return false }
+func (f *file) Rotate() { f.rotateCh <- struct{}{} }
+func (*file) SupportsColors() bool { return false }
-func (s *file) write(m *fileMessageBuf) {
+func (f *file) write(m *fileMessageBuf) {
select {
- case <-s.rotateCh:
- // Force re-opening the outfile.
- s.lastDateStr = ""
+ case <-f.rotateCh:
+ // Force re-opening the outfile next time in getWriter.
+ f.lastFileName = ""
default:
}
- writer := s.getWriter(m.now.Format("20060102"))
+ var writer *bufio.Writer
+ if f.strategy.Rotation == DailyRotation {
+ writer = f.getWriter(m.now.Format("20060102"))
+ } else {
+ writer = f.getWriter(f.strategy.FileBase)
+ }
+
writer.WriteString(m.message)
writer.WriteByte('\n')
}
-func (s *file) getWriter(dateStr string) *bufio.Writer {
- if s.lastDateStr == dateStr {
- return s.writer
+func (f *file) getWriter(name string) *bufio.Writer {
+ if f.lastFileName == name {
+ return f.writer
}
if _, err := os.Stat(config.Common.LogDir); os.IsNotExist(err) {
@@ -123,32 +134,32 @@ func (s *file) getWriter(dateStr string) *bufio.Writer {
}
}
- logFile := fmt.Sprintf("%s/%s.log", config.Common.LogDir, dateStr)
+ logFile := fmt.Sprintf("%s/%s.log", config.Common.LogDir, name)
newFd, err := os.OpenFile(logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
panic(err)
}
// Close old writer.
- if s.fd != nil {
- s.writer.Flush()
- s.fd.Close()
+ if f.fd != nil {
+ f.writer.Flush()
+ f.fd.Close()
}
- s.fd = newFd
- s.writer = bufio.NewWriterSize(s.fd, 1)
- s.lastDateStr = dateStr
+ f.fd = newFd
+ f.writer = bufio.NewWriterSize(f.fd, 1)
+ f.lastFileName = name
- return s.writer
+ return f.writer
}
-func (s *file) flush() {
- defer s.writer.Flush()
+func (f *file) flush() {
+ defer f.writer.Flush()
for {
select {
- case m := <-s.bufferCh:
- s.write(m)
+ case m := <-f.bufferCh:
+ f.write(m)
default:
return
}
diff --git a/internal/io/dlog/loggers/fout.go b/internal/io/dlog/loggers/fout.go
index 603dbe9..60c318d 100644
--- a/internal/io/dlog/loggers/fout.go
+++ b/internal/io/dlog/loggers/fout.go
@@ -12,8 +12,8 @@ type fout struct {
}
// Logs to both, a file and stdout
-func newFout() *fout {
- return &fout{file: newFile(), stdout: newStdout()}
+func newFout(strategy Strategy) *fout {
+ return &fout{file: newFile(strategy), stdout: newStdout()}
}
func (f *fout) Start(ctx context.Context, wg *sync.WaitGroup) {
diff --git a/internal/io/dlog/strategy.go b/internal/io/dlog/strategy.go
deleted file mode 100644
index 32d8298..0000000
--- a/internal/io/dlog/strategy.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package dlog
-
-import "github.com/mimecast/dtail/internal/config"
-
-// Strategy allows to specify a log rotation strategy.
-type Strategy int
-
-// Possible log strategies.
-const (
- NormalStrategy Strategy = iota
- DailyStrategy Strategy = iota
- StdoutStrategy Strategy = iota
-)
-
-func logStrategy() Strategy {
- switch config.Common.LogStrategy {
- case "daily":
- return DailyStrategy
- default:
- }
- return StdoutStrategy
-}
diff --git a/internal/io/logger/logger.go b/internal/io/logger/logger.go
deleted file mode 100644
index 905d1cf..0000000
--- a/internal/io/logger/logger.go
+++ /dev/null
@@ -1,443 +0,0 @@
-package logger
-
-import (
- "bufio"
- "context"
- "fmt"
- "os"
- "os/signal"
- "runtime"
- "strings"
- "sync"
- "syscall"
- "time"
-
- "github.com/mimecast/dtail/internal/color/brush"
- "github.com/mimecast/dtail/internal/config"
- "github.com/mimecast/dtail/internal/io/pool"
- "github.com/mimecast/dtail/internal/protocol"
-)
-
-const (
- clientStr string = "CLIENT"
- serverStr string = "SERVER"
- infoStr string = "INFO"
- warnStr string = "WARN"
- errorStr string = "ERROR"
- fatalStr string = "FATAL"
- debugStr string = "DEBUG"
- traceStr string = "TRACE"
-)
-
-// Mode specifies the configured logging mode(s)
-var Mode Modes
-
-// Strategy is the current log strattegy used.
-var strategy Strategy
-
-// Synchronise access to logging.
-var mutex sync.Mutex
-
-// File descriptor of log file when Mode.logToFile enabled.
-var fd *os.File
-
-// File write buffer of log file when Mode.logToFile enabled.
-var writer *bufio.Writer
-
-// File write buffer of stdout when Mode.logToStdout enabled.
-var stdoutWriter *bufio.Writer
-
-// Current hostname.
-var hostname string
-
-// Used to detect change of day (create one log file per day0
-var lastDateStr string
-
-// Used to make logging non-blocking.
-var fileLogBufCh chan buf
-var stdoutBufCh chan string
-
-// Stdout channel, required to pause output
-var pauseCh chan struct{}
-var resumeCh chan struct{}
-
-// Tell the logger about logrotation
-var rotateCh chan os.Signal
-
-// Override the logger with a custom callack (e.g. for the t.Log for unit tests)
-type unitTestCallback func(message string)
-
-var unitTestOkCb unitTestCallback
-var unitTestErrorCb unitTestCallback
-
-// Helper type to make logging non-blocking.
-type buf struct {
- time time.Time
- message string
-}
-
-// StartUnitTests enables to log all messages to the unit tests.
-func StartUnitTests(ctx context.Context, okCb, errCb unitTestCallback) {
- unitTestOkCb = okCb
- unitTestErrorCb = errCb
- Start(ctx, Modes{UnitTest: true})
-}
-
-// Start logging.
-func Start(ctx context.Context, mode Modes) {
- Mode = mode
-
- switch {
- case Mode.Nothing:
- return
- case Mode.Quiet:
- Mode.Trace = false
- Mode.Debug = false
- case Mode.Trace:
- Mode.Debug = true
- default:
- }
-
- strategy := logStrategy()
- stdoutWriter = bufio.NewWriter(os.Stdout)
-
- switch strategy {
- case DailyStrategy:
- _, err := os.Stat(config.Common.LogDir)
- Mode.logToFile = !os.IsNotExist(err) && !Mode.UnitTest
- Mode.logToStdout = !Mode.Server || Mode.Debug || Mode.Trace || Mode.Quiet
- case StdoutStrategy:
- fallthrough
- default:
- Mode.logToFile = !Mode.Server && !Mode.UnitTest
- Mode.logToStdout = true
- }
-
- fqdn, err := os.Hostname()
- if err != nil {
- panic(err)
- }
- s := strings.Split(fqdn, ".")
- hostname = s[0]
-
- pauseCh = make(chan struct{})
- resumeCh = make(chan struct{})
-
- // Setup logrotation
- rotateCh = make(chan os.Signal, 1)
- signal.Notify(rotateCh, syscall.SIGHUP)
-
- if Mode.logToStdout {
- stdoutBufCh = make(chan string, runtime.NumCPU()*100)
- go writeToStdout(ctx)
- }
-
- if Mode.logToFile {
- fileLogBufCh = make(chan buf, runtime.NumCPU()*100)
- go writeToFile(ctx)
- }
-}
-
-// Info message logging.
-func Info(args ...interface{}) string {
- if Mode.Server {
- return log(serverStr, infoStr, args)
- }
-
- return log(clientStr, infoStr, args)
-}
-
-// Mapreduce message logging.
-func Mapreduce(table string, data map[string]interface{}) string {
- args := make([]interface{}, len(data)+1)
-
- args[0] = fmt.Sprintf("MAPREDUCE:%s", strings.ToUpper(table))
- i := 1
- for k, v := range data {
- args[i] = fmt.Sprintf("%s=%v", k, v)
- i++
- }
-
- if Mode.Server {
- return log(serverStr, infoStr, args)
- }
-
- return log(clientStr, infoStr, args)
-}
-
-// Warn message logging.
-func Warn(args ...interface{}) string {
- if !Mode.Quiet {
- if Mode.Server {
- return log(serverStr, warnStr, args)
- }
- return log(clientStr, warnStr, args)
- }
-
- return ""
-}
-
-// Error message logging.
-func Error(args ...interface{}) string {
- if Mode.Server {
- return log(serverStr, errorStr, args)
- }
-
- return log(clientStr, errorStr, args)
-}
-
-// Fatal message logging.
-func Fatal(args ...interface{}) string {
- if Mode.Server {
- return log(serverStr, fatalStr, args)
- }
-
- return log(clientStr, fatalStr, args)
-}
-
-// FatalPanic logs an error and exists the process.
-func FatalPanic(args ...interface{}) {
- what := clientStr
- if Mode.Server {
- what = serverStr
- }
- log(what, fatalStr, args)
-
- time.Sleep(time.Second)
- mutex.Lock()
- defer mutex.Unlock()
-
- closeWriter()
- os.Exit(3)
-}
-
-// Debug message logging.
-func Debug(args ...interface{}) string {
- if Mode.Debug {
- if Mode.Server {
- return log(serverStr, debugStr, args)
- }
- return log(clientStr, debugStr, args)
- }
-
- return ""
-}
-
-// Trace message logging.
-func Trace(args ...interface{}) string {
- if Mode.Trace {
- if Mode.Server {
- return log(serverStr, traceStr, args)
- }
- return log(clientStr, traceStr, args)
- }
-
- return ""
-}
-
-// Write log line to buffer and/or log file.
-func write(what, severity, message string) {
- if Mode.logToStdout {
- line := fmt.Sprintf("%s|%s|%s|%s", what, hostname, severity, message)
-
- if config.Client.TermColorsEnable {
- line = brush.Colorfy(line)
- }
-
- stdoutBufCh <- line
- }
-
- if Mode.logToFile {
- t := time.Now()
- timeStr := t.Format("20060102-150405")
- fileLogBufCh <- buf{
- time: t,
- message: fmt.Sprintf("%s|%s|%s|%s", severity, timeStr, what, message),
- }
- }
-}
-
-// Generig log message.
-func log(what string, severity string, args []interface{}) string {
- if Mode.Nothing {
- return ""
- }
-
- sb := pool.BuilderBuffer.Get().(*strings.Builder)
-
- for i, arg := range args {
- if i > 0 {
- sb.WriteString(protocol.FieldDelimiter)
- }
-
- switch v := arg.(type) {
- case string:
- sb.WriteString(v)
- case int:
- sb.WriteString(fmt.Sprintf("%d", v))
- case error:
- sb.WriteString(v.Error())
- default:
- sb.WriteString(fmt.Sprintf("%v", v))
- }
- }
-
- message := sb.String()
- pool.RecycleBuilderBuffer(sb)
- write(what, severity, message)
- return fmt.Sprintf("%s|%s", severity, message)
-}
-
-// Raw message logging.
-func Raw(message string) {
- if Mode.Nothing {
- return
- }
-
- if Mode.logToFile {
- fileLogBufCh <- buf{time.Now(), message}
- }
-
- if Mode.logToStdout {
- if config.Client.TermColorsEnable {
- message = brush.Colorfy(message)
- }
- stdoutBufCh <- message
- }
-}
-
-// Close log writer (e.g. on change of day).
-func closeWriter() {
- if writer != nil {
- writer.Flush()
- fd.Close()
- }
-}
-
-// Return the correct log file writer
-func fileWriter(dateStr string) *bufio.Writer {
- if dateStr != lastDateStr {
- return updateFileWriter(dateStr)
- }
-
- // Check for log rotation signal
- select {
- case <-rotateCh:
- stdoutWriter.WriteString("Received signal for logrotation\n")
- return updateFileWriter(dateStr)
- default:
- }
-
- return writer
-}
-
-// Update log file writer
-func updateFileWriter(dateStr string) *bufio.Writer {
- // Detected change of day. Close current writer and create a new one.
- mutex.Lock()
- defer mutex.Unlock()
- closeWriter()
-
- if _, err := os.Stat(config.Common.LogDir); os.IsNotExist(err) {
- if err = os.MkdirAll(config.Common.LogDir, 0755); err != nil {
- panic(err)
- }
- }
-
- logFile := fmt.Sprintf("%s/%s.log", config.Common.LogDir, dateStr)
- newFd, err := os.OpenFile(logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
- if err != nil {
- panic(err)
- }
-
- fd = newFd
- writer = bufio.NewWriterSize(fd, 1)
- lastDateStr = dateStr
-
- return writer
-}
-
-// Flush all outstanding lines.
-func Flush() {
- for {
- select {
- case message := <-stdoutBufCh:
- stdoutWriter.WriteString(message)
- stdoutWriter.WriteString("\n")
- default:
- stdoutWriter.Flush()
- return
- }
- }
-}
-
-func writeToStdout(ctx context.Context) {
- for {
- select {
- case message := <-stdoutBufCh:
- stdoutWriter.WriteString(message)
- stdoutWriter.WriteString("\n")
- case <-time.After(time.Millisecond * 100):
- stdoutWriter.Flush()
- case <-pauseCh:
- PAUSE:
- for {
- select {
- case <-stdoutBufCh:
- case <-resumeCh:
- break PAUSE
- case <-ctx.Done():
- return
- }
- }
- case <-ctx.Done():
- Flush()
- return
- }
- }
-}
-
-func writeToFile(ctx context.Context) {
- for {
- select {
- case buf := <-fileLogBufCh:
- dateStr := buf.time.Format("20060102")
- w := fileWriter(dateStr)
- w.WriteString(buf.message)
- w.WriteString("\n")
- case <-pauseCh:
- PAUSE:
- for {
- select {
- case <-stdoutBufCh:
- case <-resumeCh:
- break PAUSE
- case <-ctx.Done():
- return
- }
- }
- case <-ctx.Done():
- return
- }
- }
-}
-
-// Pause logging.
-func Pause() {
- if Mode.logToStdout {
- pauseCh <- struct{}{}
- }
- if Mode.logToFile {
- pauseCh <- struct{}{}
- }
-}
-
-// Resume logging (after pausing).
-func Resume() {
- if Mode.logToStdout {
- resumeCh <- struct{}{}
- }
- if Mode.logToFile {
- resumeCh <- struct{}{}
- }
-}
diff --git a/internal/io/logger/modes.go b/internal/io/logger/modes.go
deleted file mode 100644
index 85f90a5..0000000
--- a/internal/io/logger/modes.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package logger
-
-// Modes specifies the logging mode.
-type Modes struct {
- Debug bool
- logToFile bool
- logToStdout bool
- Nothing bool
- Quiet bool
- Server bool
- Trace bool
- UnitTest bool
-}
diff --git a/internal/io/logger/strategy.go b/internal/io/logger/strategy.go
deleted file mode 100644
index 44bf393..0000000
--- a/internal/io/logger/strategy.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package logger
-
-import "github.com/mimecast/dtail/internal/config"
-
-// Strategy allows to specify a log rotation strategy.
-type Strategy int
-
-// Possible log strategies.
-const (
- NormalStrategy Strategy = iota
- DailyStrategy Strategy = iota
- StdoutStrategy Strategy = iota
-)
-
-func logStrategy() Strategy {
- switch config.Common.LogStrategy {
- case "daily":
- return DailyStrategy
- default:
- }
- return StdoutStrategy
-}