/
DirectLog.go
106 lines (86 loc) · 2.4 KB
/
DirectLog.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// ---------------------------------------------------------------------------
//
// DirectLog.go
//
// Copyright (c) 2014, Jared Chavez.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// -----------
package flog
import (
"log"
"os"
"sync"
"sync/atomic"
)
// DirectLog represents a file-backed logger and enforces a standardized
// logging format. New logging entries are written immediately to the
// backing file.
type DirectLog struct {
baseDir string
enabled int32
file *os.File
lock sync.RWMutex
logger *log.Logger
name string
}
// BaseDir returns the base directory of the file backing this DirectLog instance.
func (this *DirectLog) BaseDir() string {
this.lock.RLock()
defer this.lock.RUnlock()
return this.baseDir
}
// Close disables the DirectLog instance, flushes any remaining entries to disk, and
// then closes the backing log file.
func (this *DirectLog) Close() {
this.lock.Lock()
defer this.lock.Unlock()
this.enabled = 0
this.print("==== Close log ====")
this.file.Sync()
this.file.Close()
}
// Disable temporarily disables the DirectLog instance. New calls to Print will have no
// effect.
func (this *DirectLog) Disable() {
atomic.StoreInt32(&this.enabled, 0)
}
// Enable re-enables an DirectLog instance.
func (this *DirectLog) Enable() {
atomic.StoreInt32(&this.enabled, 1)
}
// Name returns the friendly name of the log.
func (this *DirectLog) Name() string {
this.lock.RLock()
defer this.lock.RUnlock()
return this.name
}
// Print formats and buffers a new log entry as long as the DirectLog instance
// is enabled.
func (this *DirectLog) Print(format string, v ...interface{}) {
this.lock.RLock()
defer this.lock.RUnlock()
if atomic.LoadInt32(&this.enabled) < 1 {
return
}
if v == nil {
this.print(format)
} else {
this.print(format, v...)
}
}
// print performs log entry formatting and uses a std library logger to
// write the formatted entry into the DirectLog's buffer.
func (this *DirectLog) print(format string, v ...interface{}) {
format = fixFormat(this.name, format)
if v == nil {
log.Print(format)
this.logger.Print(format)
} else {
log.Printf(format, v...)
this.logger.Printf(format, v...)
}
}