Btcd-go in log section code
Overall design
Backend
type Backend struct { w io.Writer mu sync.Mutex // ensures atomic writes flag uint32}
The main implementation of the thread-safe print, printf function, that is, format the log to be printed. W This writer as the initial parameter, can be transferred from the outside, deconstructed writer, easy to configure writer, such as Std. Out/std. ERR and other implementations of the writer interface of the struct can be.
Backend also implements a factory function that creates an instance:
func (b* Backend) Logger(subsystemTag string) Logger { return &slog{LevelInfo, subsystemTag, b}}
Slog
type slog struct { lvl Level tag string b *Backend}
This class implements all interfaces of the Interface:logger. The internal realization of the cause backend. Level to control log display levels. tag to identify the log from a subsystem subsystem.
In the form of characters, according to the fixed length output number, the length is not enough, the front with 0.
But this algorithm, as long as I is greater than 0 to work properly, so, I type to change to a uint more appropriate
// From stdlib log package.// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid// zero-padding.func itoa(buf *[]byte, i int, wid int) { // Assemble decimal in reverse order. var b [20]byte bp := len(b) - 1 for i >= 10 || wid > 1 { wid-- q := i / 10 b[bp] = byte('0' + i - q*10) bp-- i = q } // i < 10 b[bp] = byte('0' + i) *buf = append(*buf, b[bp:]...)}
The use of assigning a value of 0 to slice
// recycleBuffer puts the provided byte slice, which should have been obtain via// the buffer function, back on the free list.func recycleBuffer(b *[]byte) { *b = (*b)[:0] bufferPool.Put(b)}
The *b = (*b) [: 0] is the assignment of a byte slice B to a value of 0.
More go routine, use the pool to
var bufferPool = sync.Pool{ New: func() interface{} { b := make([]byte, 0, 120) return &b },}
If you have more than one go routine output log, you can use pool to avoid competing with the same cache, such as using the same cache, will cause other go routine hangs, and only when writer writes the data, only use the mutex to synchronize, so more efficient, use space to change time.
Reference