Monday, March 20, 2017

Golang: Quick and Easier Leveled Logging

using logfngithub.com/noypi/logfn

Example usage:
 DBG("subject=%v, tag=%v, row=%v", subject, tag, row)  

 // print stacktrace (last 8 calls)  
 DBG.PrintStackTrace(8)  

 // similar to PrintLn()  
 DBG.Ln(var1, var2, var3)  


first lets define our LogFunc:
 type LogFunc func(fmt string, params ...interface{})  


then our hero type the LogLevel:
 type LogLevel int  


our goal is to have something like:
 var (  
      CRITICAL = g_logLevel.WrapFunc(int(LogCritical), log.Printf, "[pkgname][C] ")  
      ERR      = g_logLevel.WrapFunc(int(LogError),    log.Printf, "[pkgname][E] ")  
      WARN     = g_logLevel.WrapFunc(int(LogWarning),  log.Printf, "[pkgname][W] ")  
      INFO     = g_logLevel.WrapFunc(int(LogInfo),     log.Printf, "[pkgname][I] ")  
      API      = g_logLevel.WrapFunc(int(LogApi),      log.Printf, "[pkgname][A] ")  
      DBG      = g_logLevel.WrapFunc(int(LogDebug),    log.Printf, "[pkgname][D] ")  
 )  


so, we wrap our LogFunc, with the code:
 func (this *LogLevel) WrapFunc(level int, fn LogFunc, prefix string) LogFunc {  
      prefix = strings.Replace(prefix, "%", "", -1)  
      return func(s string, as ...interface{}) {  
           if level <= int(*this) {  
                fn(prefix+s, as...)  
           }  
      }  
 }  


finally, a way to set the log level:
 func (this *LogLevel) SetLevel(n int) {  
      *this = (LogLevel)(n)  
 }  


we defined our levels as:
 const (  
      LogCritical LogLevel = iota  
      LogError  
      LogWarning  
      LogInfo  
      LogApi  
      LogDebug  
 )  

Thanks.