github.com/balzaczyy/golucene@v0.0.0-20151210033525-d0be9ee89713/core/util/infoStream.go (about) 1 package util 2 3 import ( 4 "fmt" 5 "io" 6 "log" 7 "os" 8 "sync" 9 "sync/atomic" 10 "time" 11 ) 12 13 // util/InfoStream.java 14 15 /* 16 Debugging API for Lucene classes such as IndexWriter and SegmentInfos. 17 18 NOTE: Enabling infostreams may cause performance degradation in some 19 components. 20 */ 21 type InfoStream interface { 22 io.Closer 23 // Clone() InfoStream 24 // prints a message 25 Message(component, message string, args ...interface{}) 26 // returns true if messages are enabled and should be posted. 27 IsEnabled(component string) bool 28 } 29 30 // Instance of InfoStream that does no logging at all. 31 var NO_OUTPUT = NoOutput(true) 32 33 type NoOutput bool 34 35 func (is NoOutput) Message(component, message string, args ...interface{}) { 36 panic("message() should not be called when isEnabled returns false") 37 } 38 39 func (is NoOutput) IsEnabled(component string) bool { 40 return false 41 } 42 43 func (is NoOutput) Close() error { return nil } 44 45 var defaultInfoStream InfoStream = NO_OUTPUT 46 var defaultInfoStreamLock = &sync.Mutex{} 47 48 // The default InfoStream used by a newly instantiated classes. 49 func DefaultInfoStream() InfoStream { 50 defaultInfoStreamLock.Lock() // synchronized 51 defer defaultInfoStreamLock.Unlock() 52 return defaultInfoStream 53 } 54 55 /* 56 Sets the default InfoStream used by a newly instantiated classes. It 57 cannot be nil, to disable logging use NO_OUTPUT. 58 */ 59 func SetDefaultInfoStream(infoStream InfoStream) { 60 log.Print("Setting default infoStream...") 61 defaultInfoStreamLock.Lock() // synchronized 62 defer defaultInfoStreamLock.Unlock() 63 assert2(infoStream != nil, `Cannot set InfoStream default implementation to nil. 64 To disable logging use NO_OUTPUT.`) 65 defaultInfoStream = infoStream 66 } 67 68 // util/PrintStreamInfoStream.java 69 70 var MESSAGE_ID int32 // atomic 71 const FORMAT = "2006/01/02 15:04:05" 72 73 /* 74 InfoStream implementation over an io.Writer such as os.Stdout 75 */ 76 type PrintStreamInfoStream struct { 77 stream io.Writer 78 messageId int32 79 } 80 81 func NewPrintStreamInfoStream(w io.Writer) *PrintStreamInfoStream { 82 return &PrintStreamInfoStream{w, atomic.AddInt32(&MESSAGE_ID, 1) - 1} 83 } 84 85 func (is *PrintStreamInfoStream) Message(component, 86 message string, args ...interface{}) { 87 fmt.Fprintf(is.stream, "%4v %v [%v] %v\n", component, is.messageId, 88 time.Now().Format(FORMAT), fmt.Sprintf(message, args...)) 89 } 90 91 func (is *PrintStreamInfoStream) IsEnabled(component string) bool { 92 return "TP" != component 93 } 94 95 func (is *PrintStreamInfoStream) Close() error { 96 if !is.isSystemStream() { 97 return is.Close() 98 } 99 return nil 100 } 101 102 func (is *PrintStreamInfoStream) isSystemStream() bool { 103 return is.stream == os.Stdout || is.stream == os.Stderr 104 }