├── .travis.yml ├── LICENSE ├── README.md ├── examples ├── example.go └── example.png ├── logger.go └── logger_test.go /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 1.2 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Amanpreet Singh 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # go-logger 3 | 4 | [![Build Status](https://travis-ci.org/apsdehal/go-logger.svg?branch=master)](https://travis-ci.org/apsdehal/go-logger) 5 | [![GoDoc](https://godoc.org/github.com/apsdehal/go-logger?status.svg)](http://godoc.org/github.com/apsdehal/go-logger) 6 | 7 | A simple go logger for easy logging in your programs. Allows setting custom format for messages. 8 | 9 | # Preview 10 | 11 | [![Example Output](examples/example.png)](examples/example.go) 12 | 13 | 14 | # Install 15 | 16 | `go get github.com/apsdehal/go-logger` 17 | 18 | Use `go get -u` to update the package. 19 | 20 | # Example 21 | 22 | Example [program](examples/example.go) demonstrates how to use the logger. See below for __formatting__ instructions. 23 | 24 | 25 | ```go 26 | package main 27 | 28 | import ( 29 | "github.com/apsdehal/go-logger" 30 | "os" 31 | ) 32 | 33 | func main () { 34 | // Get the instance for logger class, "test" is the module name, 1 is used to 35 | // state if we want coloring 36 | // Third option is optional and is instance of type io.Writer, defaults to os.Stderr 37 | log, err := logger.New("test", 1, os.Stdout) 38 | if err != nil { 39 | panic(err) // Check for error 40 | } 41 | 42 | // Critically log critical 43 | log.Critical("This is Critical!") 44 | log.CriticalF("%+v", err) 45 | // You can also use fmt compliant naming scheme such as log.Criticalf, log.Panicf etc 46 | // with small 'f' 47 | 48 | // Debug 49 | // Since default logging level is Info this won't print anything 50 | log.Debug("This is Debug!") 51 | log.DebugF("Here are some numbers: %d %d %f", 10, -3, 3.14) 52 | // Give the Warning 53 | log.Warning("This is Warning!") 54 | log.WarningF("This is Warning!") 55 | // Show the error 56 | log.Error("This is Error!") 57 | log.ErrorF("This is Error!") 58 | // Notice 59 | log.Notice("This is Notice!") 60 | log.NoticeF("%s %s", "This", "is Notice!") 61 | // Show the info 62 | log.Info("This is Info!") 63 | log.InfoF("This is %s!", "Info") 64 | 65 | log.StackAsError("Message before printing stack"); 66 | 67 | // Show warning with format 68 | log.SetFormat("[%{module}] [%{level}] %{message}") 69 | log.Warning("This is Warning!") // output: "[test] [WARNING] This is Warning!" 70 | // Also you can set your format as default format for all new loggers 71 | logger.SetDefaultFormat("%{message}") 72 | log2, _ := logger.New("pkg", 1, os.Stdout) 73 | log2.Error("This is Error!") // output: "This is Error!" 74 | 75 | // Use log levels to set your log priority 76 | log2.SetLogLevel(DebugLevel) 77 | // This will be printed 78 | log2.Debug("This is debug!") 79 | log2.SetLogLevel(WarningLevel) 80 | // This won't be printed 81 | log2.Info("This is an error!") 82 | } 83 | ``` 84 | 85 | 86 | # Formatting 87 | 88 | By default all log messages have format that you can see above (on pic). 89 | But you can override the default format and set format that you want. 90 | 91 | You can do it for Logger instance (after creating logger) ... 92 | ```go 93 | log, _ := logger.New("pkgname", 1) 94 | log.SetFormat(format) 95 | ``` 96 | ... or for package 97 | ```go 98 | logger.SetDefaultFormat(format) 99 | ``` 100 | If you do it for package, all existing loggers will print log messages with format that these used already. 101 | But all newest loggers (which will be created after changing format for package) will use your specified format. 102 | 103 | But anyway after this, you can still set format of message for specific Logger instance. 104 | 105 | Format of log message must contains verbs that represent some info about current log entry. 106 | Ofc, format can contain not only verbs but also something else (for example text, digits, symbols, etc) 107 | 108 | ### Format verbs: 109 | You can use the following verbs: 110 | ``` 111 | %{id} - means number of current log message 112 | %{module} - means module name (that you passed to func New()) 113 | %{time} - means current time in format "2006-01-02 15:04:05" 114 | %{time:format} - means current time in format that you want 115 | (supports all formats supported by go package "time") 116 | %{level} - means level name (upper case) of log message ("ERROR", "DEBUG", etc) 117 | %{lvl} - means first 3 letters of level name (upper case) of log message ("ERR", "DEB", etc) 118 | %{file} - means name of file in what you wanna write log 119 | %{filename} - means the same as %{file} 120 | %{line} - means line number of file in what you wanna write log 121 | %{message} - means your log message 122 | ``` 123 | Non-existent verbs (like ```%{nonex-verb}``` or ```%{}```) will be replaced by an empty string. 124 | Invalid verbs (like ```%{inv-verb```) will be treated as plain text. 125 | 126 | # Tests 127 | 128 | Run: 129 | - `go test logger` to run test on logger. 130 | - `go test -bench=.` for benchmarks. 131 | 132 | ## Thanks 133 | 134 | Thanks goes to all go-loggers out there which I used as reference. 135 | 136 | ## Contributors 137 | 138 | Following contributors have made major contributions to go-logger: 139 | 140 | - [@qioalice](https://github.com/qioalice) 141 | - [@gjvnq](https://github.com/gjvnq) 142 | - [@maezen](https://github.com/maezen) 143 | 144 | ## License 145 | 146 | The [BSD 3-Clause license](http://opensource.org/licenses/BSD-3-Clause), the same as the [Go language](http://golang.org/LICENSE). 147 | -------------------------------------------------------------------------------- /examples/example.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "github.com/apsdehal/go-logger" 6 | ) 7 | 8 | func main () { 9 | // Get the instance for logger class 10 | // Third option is optional and is instance of type io.Writer, defaults to os.Stderr 11 | log, err := logger.New("test", 1, os.Stdout) 12 | if err != nil { 13 | panic(err) // Check for error 14 | } 15 | 16 | // Critically log critical 17 | log.Critical("This is Critical!") 18 | // Debug 19 | log.Debug("This is Debug!") 20 | // Give the Warning 21 | log.Warning("This is Warning!") 22 | // Show the error 23 | log.Error("This is Error!") 24 | // Notice 25 | log.Notice("This is Notice!") 26 | // Show the info 27 | log.Info("This is Info!") 28 | 29 | // Show warning with format message 30 | log.SetFormat("[%{module}] [%{level}] %{message}") 31 | log.Warning("This is Warning!") 32 | // Also you can set your format as default format for all new loggers 33 | logger.SetDefaultFormat("%{message}") 34 | log2, _ := logger.New("pkg", 1, os.Stdout) 35 | log2.Error("This is Error!") 36 | } -------------------------------------------------------------------------------- /examples/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apsdehal/go-logger/b0d6ccfee0e6fb798b2dab6b21ac498dbc5e9784/examples/example.png -------------------------------------------------------------------------------- /logger.go: -------------------------------------------------------------------------------- 1 | // Package name declaration 2 | package logger 3 | 4 | // Import packages 5 | import ( 6 | "bytes" 7 | "fmt" 8 | "io" 9 | "log" 10 | "os" 11 | "path" 12 | "runtime" 13 | "strings" 14 | "sync/atomic" 15 | "time" 16 | ) 17 | 18 | var ( 19 | // Map for the various codes of colors 20 | colors map[LogLevel]string 21 | 22 | // Map from format's placeholders to printf verbs 23 | phfs map[string]string 24 | 25 | // Contains color strings for stdout 26 | logNo uint64 27 | 28 | // Default format of log message 29 | defFmt = "#%[1]d %[2]s %[4]s:%[5]d ▶ %.3[6]s %[7]s" 30 | 31 | // Default format of time 32 | defTimeFmt = "2006-01-02 15:04:05" 33 | ) 34 | 35 | // LogLevel type 36 | type LogLevel int 37 | 38 | // Color numbers for stdout 39 | const ( 40 | Black = (iota + 30) 41 | Red 42 | Green 43 | Yellow 44 | Blue 45 | Magenta 46 | Cyan 47 | White 48 | ) 49 | 50 | // Log Level 51 | const ( 52 | CriticalLevel LogLevel = iota + 1 53 | ErrorLevel 54 | WarningLevel 55 | NoticeLevel 56 | InfoLevel 57 | DebugLevel 58 | ) 59 | 60 | // Worker class, Worker is a log object used to log messages and Color specifies 61 | // if colored output is to be produced 62 | type Worker struct { 63 | Minion *log.Logger 64 | Color int 65 | format string 66 | timeFormat string 67 | level LogLevel 68 | } 69 | 70 | // Info class, Contains all the info on what has to logged, time is the current time, Module is the specific module 71 | // For which we are logging, level is the state, importance and type of message logged, 72 | // Message contains the string to be logged, format is the format of string to be passed to sprintf 73 | type Info struct { 74 | Id uint64 75 | Time string 76 | Module string 77 | Level LogLevel 78 | Line int 79 | Filename string 80 | Message string 81 | //format string 82 | } 83 | 84 | // Logger class that is an interface to user to log messages, Module is the module for which we are testing 85 | // worker is variable of Worker class that is used in bottom layers to log the message 86 | type Logger struct { 87 | Module string 88 | worker *Worker 89 | } 90 | 91 | // init pkg 92 | func init() { 93 | initColors() 94 | initFormatPlaceholders() 95 | } 96 | 97 | // Returns a proper string to be outputted for a particular info 98 | func (r *Info) Output(format string) string { 99 | msg := fmt.Sprintf(format, 100 | r.Id, // %[1] // %{id} 101 | r.Time, // %[2] // %{time[:fmt]} 102 | r.Module, // %[3] // %{module} 103 | r.Filename, // %[4] // %{filename} 104 | r.Line, // %[5] // %{line} 105 | r.logLevelString(), // %[6] // %{level} 106 | r.Message, // %[7] // %{message} 107 | ) 108 | // Ignore printf errors if len(args) > len(verbs) 109 | if i := strings.LastIndex(msg, "%!(EXTRA"); i != -1 { 110 | return msg[:i] 111 | } 112 | return msg 113 | } 114 | 115 | // Analyze and represent format string as printf format string and time format 116 | func parseFormat(format string) (msgfmt, timefmt string) { 117 | if len(format) < 10 /* (len of "%{message} */ { 118 | return defFmt, defTimeFmt 119 | } 120 | timefmt = defTimeFmt 121 | idx := strings.IndexRune(format, '%') 122 | for idx != -1 { 123 | msgfmt += format[:idx] 124 | format = format[idx:] 125 | if len(format) > 2 { 126 | if format[1] == '{' { 127 | // end of curr verb pos 128 | if jdx := strings.IndexRune(format, '}'); jdx != -1 { 129 | // next verb pos 130 | idx = strings.Index(format[1:], "%{") 131 | // incorrect verb found ("...%{wefwef ...") but after 132 | // this, new verb (maybe) exists ("...%{inv %{verb}...") 133 | if idx != -1 && idx < jdx { 134 | msgfmt += "%%" 135 | format = format[1:] 136 | continue 137 | } 138 | // get verb and arg 139 | verb, arg := ph2verb(format[:jdx+1]) 140 | msgfmt += verb 141 | // check if verb is time 142 | // here you can handle args for other verbs 143 | if verb == `%[2]s` && arg != "" /* %{time} */ { 144 | timefmt = arg 145 | } 146 | format = format[jdx+1:] 147 | } else { 148 | format = format[1:] 149 | } 150 | } else { 151 | msgfmt += "%%" 152 | format = format[1:] 153 | } 154 | } 155 | idx = strings.IndexRune(format, '%') 156 | } 157 | msgfmt += format 158 | return 159 | } 160 | 161 | // translate format placeholder to printf verb and some argument of placeholder 162 | // (now used only as time format) 163 | func ph2verb(ph string) (verb string, arg string) { 164 | n := len(ph) 165 | if n < 4 { 166 | return ``, `` 167 | } 168 | if ph[0] != '%' || ph[1] != '{' || ph[n-1] != '}' { 169 | return ``, `` 170 | } 171 | idx := strings.IndexRune(ph, ':') 172 | if idx == -1 { 173 | return phfs[ph], `` 174 | } 175 | verb = phfs[ph[:idx]+"}"] 176 | arg = ph[idx+1 : n-1] 177 | return 178 | } 179 | 180 | // Returns an instance of worker class, prefix is the string attached to every log, 181 | // flag determine the log params, color parameters verifies whether we need colored outputs or not 182 | func NewWorker(prefix string, flag int, color int, out io.Writer) *Worker { 183 | return &Worker{Minion: log.New(out, prefix, flag), Color: color, format: defFmt, timeFormat: defTimeFmt} 184 | } 185 | 186 | func SetDefaultFormat(format string) { 187 | defFmt, defTimeFmt = parseFormat(format) 188 | } 189 | 190 | func (w *Worker) SetFormat(format string) { 191 | w.format, w.timeFormat = parseFormat(format) 192 | } 193 | 194 | func (l *Logger) SetFormat(format string) { 195 | l.worker.SetFormat(format) 196 | } 197 | 198 | func (w *Worker) SetLogLevel(level LogLevel) { 199 | w.level = level 200 | } 201 | 202 | func (l *Logger) SetLogLevel(level LogLevel) { 203 | l.worker.level = level 204 | } 205 | 206 | // Function of Worker class to log a string based on level 207 | func (w *Worker) Log(level LogLevel, calldepth int, info *Info) error { 208 | 209 | if w.level < level { 210 | return nil 211 | } 212 | 213 | if w.Color != 0 { 214 | buf := &bytes.Buffer{} 215 | buf.Write([]byte(colors[level])) 216 | buf.Write([]byte(info.Output(w.format))) 217 | buf.Write([]byte("\033[0m")) 218 | return w.Minion.Output(calldepth+1, buf.String()) 219 | } else { 220 | return w.Minion.Output(calldepth+1, info.Output(w.format)) 221 | } 222 | } 223 | 224 | // Returns a proper string to output for colored logging 225 | func colorString(color int) string { 226 | return fmt.Sprintf("\033[%dm", int(color)) 227 | } 228 | 229 | // Initializes the map of colors 230 | func initColors() { 231 | colors = map[LogLevel]string{ 232 | CriticalLevel: colorString(Magenta), 233 | ErrorLevel: colorString(Red), 234 | WarningLevel: colorString(Yellow), 235 | NoticeLevel: colorString(Green), 236 | DebugLevel: colorString(Cyan), 237 | InfoLevel: colorString(White), 238 | } 239 | } 240 | 241 | // Initializes the map of placeholders 242 | func initFormatPlaceholders() { 243 | phfs = map[string]string{ 244 | "%{id}": "%[1]d", 245 | "%{time}": "%[2]s", 246 | "%{module}": "%[3]s", 247 | "%{filename}": "%[4]s", 248 | "%{file}": "%[4]s", 249 | "%{line}": "%[5]d", 250 | "%{level}": "%[6]s", 251 | "%{lvl}": "%.3[6]s", 252 | "%{message}": "%[7]s", 253 | } 254 | } 255 | 256 | // Returns a new instance of logger class, module is the specific module for which we are logging 257 | // , color defines whether the output is to be colored or not, out is instance of type io.Writer defaults 258 | // to os.Stderr 259 | func New(args ...interface{}) (*Logger, error) { 260 | //initColors() 261 | 262 | var module string = "DEFAULT" 263 | var color int = 1 264 | var out io.Writer = os.Stderr 265 | var level LogLevel = InfoLevel 266 | 267 | for _, arg := range args { 268 | switch t := arg.(type) { 269 | case string: 270 | module = t 271 | case int: 272 | color = t 273 | case io.Writer: 274 | out = t 275 | case LogLevel: 276 | level = t 277 | default: 278 | panic("logger: Unknown argument") 279 | } 280 | } 281 | newWorker := NewWorker("", 0, color, out) 282 | newWorker.SetLogLevel(level) 283 | return &Logger{Module: module, worker: newWorker}, nil 284 | } 285 | 286 | // The log commnand is the function available to user to log message, lvl specifies 287 | // the degree of the messagethe user wants to log, message is the info user wants to log 288 | func (l *Logger) Log(lvl LogLevel, message string) { 289 | l.log_internal(lvl, message, 2) 290 | } 291 | 292 | func (l *Logger) log_internal(lvl LogLevel, message string, pos int) { 293 | //var formatString string = "#%d %s [%s] %s:%d ▶ %.3s %s" 294 | _, filename, line, _ := runtime.Caller(pos) 295 | filename = path.Base(filename) 296 | info := &Info{ 297 | Id: atomic.AddUint64(&logNo, 1), 298 | Time: time.Now().Format(l.worker.timeFormat), 299 | Module: l.Module, 300 | Level: lvl, 301 | Message: message, 302 | Filename: filename, 303 | Line: line, 304 | //format: formatString, 305 | } 306 | l.worker.Log(lvl, 2, info) 307 | } 308 | 309 | // Fatal is just like func l.Critical logger except that it is followed by exit to program 310 | func (l *Logger) Fatal(message string) { 311 | l.log_internal(CriticalLevel, message, 2) 312 | os.Exit(1) 313 | } 314 | 315 | // FatalF is just like func l.CriticalF logger except that it is followed by exit to program 316 | func (l *Logger) FatalF(format string, a ...interface{}) { 317 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 318 | os.Exit(1) 319 | } 320 | 321 | // FatalF is just like func l.CriticalF logger except that it is followed by exit to program 322 | func (l *Logger) Fatalf(format string, a ...interface{}) { 323 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 324 | os.Exit(1) 325 | } 326 | 327 | // Panic is just like func l.Critical except that it is followed by a call to panic 328 | func (l *Logger) Panic(message string) { 329 | l.log_internal(CriticalLevel, message, 2) 330 | panic(message) 331 | } 332 | 333 | // PanicF is just like func l.CriticalF except that it is followed by a call to panic 334 | func (l *Logger) PanicF(format string, a ...interface{}) { 335 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 336 | panic(fmt.Sprintf(format, a...)) 337 | } 338 | 339 | // PanicF is just like func l.CriticalF except that it is followed by a call to panic 340 | func (l *Logger) Panicf(format string, a ...interface{}) { 341 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 342 | panic(fmt.Sprintf(format, a...)) 343 | } 344 | 345 | // Critical logs a message at a Critical Level 346 | func (l *Logger) Critical(message string) { 347 | l.log_internal(CriticalLevel, message, 2) 348 | } 349 | 350 | // CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf 351 | func (l *Logger) CriticalF(format string, a ...interface{}) { 352 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 353 | } 354 | 355 | // CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf 356 | func (l *Logger) Criticalf(format string, a ...interface{}) { 357 | l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) 358 | } 359 | 360 | // Error logs a message at Error level 361 | func (l *Logger) Error(message string) { 362 | l.log_internal(ErrorLevel, message, 2) 363 | } 364 | 365 | // ErrorF logs a message at Error level using the same syntax and options as fmt.Printf 366 | func (l *Logger) ErrorF(format string, a ...interface{}) { 367 | l.log_internal(ErrorLevel, fmt.Sprintf(format, a...), 2) 368 | } 369 | 370 | // ErrorF logs a message at Error level using the same syntax and options as fmt.Printf 371 | func (l *Logger) Errorf(format string, a ...interface{}) { 372 | l.log_internal(ErrorLevel, fmt.Sprintf(format, a...), 2) 373 | } 374 | 375 | // Warning logs a message at Warning level 376 | func (l *Logger) Warning(message string) { 377 | l.log_internal(WarningLevel, message, 2) 378 | } 379 | 380 | // WarningF logs a message at Warning level using the same syntax and options as fmt.Printf 381 | func (l *Logger) WarningF(format string, a ...interface{}) { 382 | l.log_internal(WarningLevel, fmt.Sprintf(format, a...), 2) 383 | } 384 | 385 | // WarningF logs a message at Warning level using the same syntax and options as fmt.Printf 386 | func (l *Logger) Warningf(format string, a ...interface{}) { 387 | l.log_internal(WarningLevel, fmt.Sprintf(format, a...), 2) 388 | } 389 | 390 | // Notice logs a message at Notice level 391 | func (l *Logger) Notice(message string) { 392 | l.log_internal(NoticeLevel, message, 2) 393 | } 394 | 395 | // NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf 396 | func (l *Logger) NoticeF(format string, a ...interface{}) { 397 | l.log_internal(NoticeLevel, fmt.Sprintf(format, a...), 2) 398 | } 399 | 400 | // NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf 401 | func (l *Logger) Noticef(format string, a ...interface{}) { 402 | l.log_internal(NoticeLevel, fmt.Sprintf(format, a...), 2) 403 | } 404 | 405 | // Info logs a message at Info level 406 | func (l *Logger) Info(message string) { 407 | l.log_internal(InfoLevel, message, 2) 408 | } 409 | 410 | // InfoF logs a message at Info level using the same syntax and options as fmt.Printf 411 | func (l *Logger) InfoF(format string, a ...interface{}) { 412 | l.log_internal(InfoLevel, fmt.Sprintf(format, a...), 2) 413 | } 414 | 415 | // InfoF logs a message at Info level using the same syntax and options as fmt.Printf 416 | func (l *Logger) Infof(format string, a ...interface{}) { 417 | l.log_internal(InfoLevel, fmt.Sprintf(format, a...), 2) 418 | } 419 | 420 | // Debug logs a message at Debug level 421 | func (l *Logger) Debug(message string) { 422 | l.log_internal(DebugLevel, message, 2) 423 | } 424 | 425 | // DebugF logs a message at Debug level using the same syntax and options as fmt.Printf 426 | func (l *Logger) DebugF(format string, a ...interface{}) { 427 | l.log_internal(DebugLevel, fmt.Sprintf(format, a...), 2) 428 | } 429 | 430 | // DebugF logs a message at Debug level using the same syntax and options as fmt.Printf 431 | func (l *Logger) Debugf(format string, a ...interface{}) { 432 | l.log_internal(DebugLevel, fmt.Sprintf(format, a...), 2) 433 | } 434 | 435 | // Prints this goroutine's execution stack as an error with an optional message at the begining 436 | func (l *Logger) StackAsError(message string) { 437 | if message == "" { 438 | message = "Stack info" 439 | } 440 | message += "\n" 441 | l.log_internal(ErrorLevel, message+Stack(), 2) 442 | } 443 | 444 | // Prints this goroutine's execution stack as critical with an optional message at the begining 445 | func (l *Logger) StackAsCritical(message string) { 446 | if message == "" { 447 | message = "Stack info" 448 | } 449 | message += "\n" 450 | l.log_internal(CriticalLevel, message+Stack(), 2) 451 | } 452 | 453 | // Returns a string with the execution stack for this goroutine 454 | func Stack() string { 455 | buf := make([]byte, 1000000) 456 | runtime.Stack(buf, false) 457 | return string(buf) 458 | } 459 | 460 | // Returns the loglevel as string 461 | func (info *Info) logLevelString() string { 462 | logLevels := [...]string{ 463 | "CRITICAL", 464 | "ERROR", 465 | "WARNING", 466 | "NOTICE", 467 | "INFO", 468 | "DEBUG", 469 | } 470 | return logLevels[info.Level-1] 471 | } 472 | -------------------------------------------------------------------------------- /logger_test.go: -------------------------------------------------------------------------------- 1 | package logger 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "math" 7 | "os" 8 | "strings" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func BenchmarkLoggerLog(b *testing.B) { 14 | b.StopTimer() 15 | log, err := New("test", 1) 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | var tests = []struct { 21 | level LogLevel 22 | message string 23 | }{ 24 | { 25 | CriticalLevel, 26 | "Critical Logging", 27 | }, 28 | { 29 | ErrorLevel, 30 | "Error logging", 31 | }, 32 | { 33 | WarningLevel, 34 | "Warning logging", 35 | }, 36 | { 37 | NoticeLevel, 38 | "Notice Logging", 39 | }, 40 | { 41 | InfoLevel, 42 | "Info Logging", 43 | }, 44 | { 45 | DebugLevel, 46 | "Debug logging", 47 | }, 48 | } 49 | 50 | b.StartTimer() 51 | for _, test := range tests { 52 | for n := 0; n <= b.N; n++ { 53 | log.Log(test.level, test.message) 54 | } 55 | } 56 | } 57 | 58 | func BenchmarkLoggerNew(b *testing.B) { 59 | for n := 0; n <= b.N; n++ { 60 | log, err := New("test", 1) 61 | if err != nil && log == nil { 62 | panic(err) 63 | } 64 | } 65 | } 66 | 67 | func TestLoggerNew(t *testing.T) { 68 | log, err := New("test", 1) 69 | if err != nil { 70 | panic(err) 71 | } 72 | if log.Module != "test" { 73 | t.Errorf("Unexpected module: %s", log.Module) 74 | } 75 | } 76 | 77 | func TestColorString(t *testing.T) { 78 | colorCode := colorString(40) 79 | if colorCode != "\033[40m" { 80 | t.Errorf("Unexpected string: %s", colorCode) 81 | } 82 | } 83 | 84 | func TestInitColors(t *testing.T) { 85 | //initColors() 86 | var tests = []struct { 87 | level LogLevel 88 | color int 89 | colorString string 90 | }{ 91 | { 92 | CriticalLevel, 93 | Magenta, 94 | "\033[35m", 95 | }, 96 | { 97 | ErrorLevel, 98 | Red, 99 | "\033[31m", 100 | }, 101 | { 102 | WarningLevel, 103 | Yellow, 104 | "\033[33m", 105 | }, 106 | { 107 | NoticeLevel, 108 | Green, 109 | "\033[32m", 110 | }, 111 | { 112 | InfoLevel, 113 | White, 114 | "\033[37m", 115 | }, 116 | { 117 | DebugLevel, 118 | Cyan, 119 | "\033[36m", 120 | }, 121 | } 122 | 123 | for _, test := range tests { 124 | if colors[test.level] != test.colorString { 125 | t.Errorf("Unexpected color string %d", test.color) 126 | } 127 | } 128 | } 129 | 130 | func TestNewWorker(t *testing.T) { 131 | var worker *Worker = NewWorker("", 0, 1, os.Stderr) 132 | if worker.Minion == nil { 133 | t.Errorf("Minion was not established") 134 | } 135 | } 136 | 137 | func BenchmarkNewWorker(b *testing.B) { 138 | for n := 0; n <= b.N; n++ { 139 | worker := NewWorker("", 0, 1, os.Stderr) 140 | if worker == nil { 141 | panic("Failed to initiate worker") 142 | } 143 | } 144 | } 145 | 146 | func TestLogger_SetFormat(t *testing.T) { 147 | var buf bytes.Buffer 148 | log, err := New("pkgname", 0, &buf) 149 | if err != nil || log == nil { 150 | panic(err) 151 | } 152 | 153 | log.SetLogLevel(DebugLevel) 154 | log.Debug("Test") 155 | log.SetLogLevel(InfoLevel) 156 | 157 | want := time.Now().Format("2006-01-02 15:04:05") 158 | want = fmt.Sprintf("#1 %s logger_test.go:154 ▶ DEB Test\n", want) 159 | have := buf.String() 160 | if have != want { 161 | t.Errorf("\nWant: %sHave: %s", want, have) 162 | } 163 | format := 164 | "text123 %{id} " + // text and digits before id 165 | "!@#$% %{time:Monday, 2006 Jan 01, 15:04:05} " + // symbols before time with spec format 166 | "a{b %{module} " + // brace with text that should be just text before verb 167 | "a}b %{filename} " + // brace with text that should be just text before verb 168 | "%% %{file} " + // percent symbols before verb 169 | "%{%{line} " + // percent symbol with brace before verb w/o space 170 | "%{nonex_verb} %{lvl} " + // nonexistent verb berfore real verb 171 | "%{incorr_verb %{level} " + // incorrect verb before real verb 172 | "%{} [%{message}]" // empty verb before message in sq brackets 173 | buf.Reset() 174 | log.SetFormat(format) 175 | log.Error("This is Error!") 176 | now := time.Now() 177 | want = fmt.Sprintf( 178 | "text123 2 "+ 179 | "!@#$%% %s "+ 180 | "a{b pkgname "+ 181 | "a}b logger_test.go "+ 182 | "%%%% logger_test.go "+ // it's printf, escaping %, don't forget 183 | "%%{175 "+ 184 | " ERR "+ 185 | "%%{incorr_verb ERROR "+ 186 | " [This is Error!]\n", 187 | now.Format("Monday, 2006 Jan 01, 15:04:05"), 188 | ) 189 | have = buf.String() 190 | if want != have { 191 | t.Errorf("\nWant: %sHave: %s", want, have) 192 | want_len := len(want) 193 | have_len := len(have) 194 | min := int(math.Min(float64(want_len), float64(have_len))) 195 | if want_len != have_len { 196 | t.Errorf("Diff lens: Want: %d, Have: %d.\n", want_len, have_len) 197 | } 198 | for i := 0; i < min; i++ { 199 | if want[i] != have[i] { 200 | t.Errorf("Differents starts at %d pos (\"%c\" != \"%c\")\n", 201 | i, want[i], have[i]) 202 | break 203 | } 204 | } 205 | } 206 | } 207 | 208 | func TestSetDefaultFormat(t *testing.T) { 209 | SetDefaultFormat("%{module} %{lvl} %{message}") 210 | var buf bytes.Buffer 211 | log, err := New("pkgname", 0, &buf) 212 | if err != nil || log == nil { 213 | panic(err) 214 | } 215 | log.Criticalf("Test %d", 123) 216 | want := "pkgname CRI Test 123\n" 217 | have := buf.String() 218 | if want != have { 219 | t.Errorf("\nWant: %sHave: %s", want, have) 220 | } 221 | } 222 | 223 | func TestLogLevel(t *testing.T) { 224 | 225 | var tests = []struct { 226 | level LogLevel 227 | message string 228 | }{ 229 | { 230 | CriticalLevel, 231 | "Critical Logging", 232 | }, 233 | { 234 | ErrorLevel, 235 | "Error logging", 236 | }, 237 | 238 | { 239 | WarningLevel, 240 | "Warning logging", 241 | }, 242 | { 243 | NoticeLevel, 244 | "Notice Logging", 245 | }, 246 | { 247 | InfoLevel, 248 | "Info Logging", 249 | }, 250 | { 251 | DebugLevel, 252 | "Debug logging", 253 | }, 254 | } 255 | 256 | var buf bytes.Buffer 257 | log, err := New("pkgname", 0, &buf) 258 | if err != nil { 259 | panic(err) 260 | } 261 | 262 | for i, test := range tests { 263 | log.SetLogLevel(test.level) 264 | 265 | log.Critical("Log Critical") 266 | log.Error("Log Error") 267 | log.Warning("Log Warning") 268 | log.Notice("Log Notice") 269 | log.Info("Log Info") 270 | log.Debug("Log Debug") 271 | 272 | // Count output lines from logger 273 | count := strings.Count(buf.String(), "\n") 274 | if i+1 != count { 275 | t.Error() 276 | } 277 | buf.Reset() 278 | } 279 | } 280 | --------------------------------------------------------------------------------