]> ruderich.org/simon Gitweb - safcm/safcm.git/blobdiff - frontend/log.go
safcm: move logEvent() to frontend package
[safcm/safcm.git] / frontend / log.go
index 33fa1d0e24e68e15211b489067dfb77dfc15b40e..aed57dddca4be9afde6f0c690fdc2bf0d0a970d8 100644 (file)
@@ -18,6 +18,9 @@
 package frontend
 
 import (
+       "fmt"
+       "log"
+
        "ruderich.org/simon/safcm"
        "ruderich.org/simon/safcm/rpc"
 )
@@ -50,3 +53,67 @@ func (l *Loop) Log(host Host, level safcm.LogLevel, escaped bool,
                Escaped: escaped,
        }
 }
+
+// LogEvent logs events using the log package. It can be used to implement
+// Loop.LogEventFunc. It's used by cmd/safcm to log events.
+func LogEvent(x Event, level safcm.LogLevel, isTTY bool,
+       failed *bool) {
+
+       // We have multiple event sources so this is somewhat ugly.
+       var prefix, data string
+       var color Color
+       if x.Error != nil {
+               prefix = "[error]"
+               data = x.Error.Error()
+               color = ColorRed
+               // We logged an error, tell the caller
+               *failed = true
+       } else if x.Log.Level != 0 {
+               if level < x.Log.Level {
+                       return
+               }
+               // LogError and LogDebug3 should not occur here
+               switch x.Log.Level {
+               case safcm.LogInfo:
+                       prefix = "[info]"
+               case safcm.LogVerbose:
+                       prefix = "[verbose]"
+               case safcm.LogDebug:
+                       prefix = "[debug]"
+               case safcm.LogDebug2:
+                       prefix = "[debug2]"
+               default:
+                       prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
+                       color = ColorRed
+               }
+               data = x.Log.Text
+       } else {
+               switch x.ConnEvent.Type {
+               case rpc.ConnEventStderr:
+                       prefix = "[stderr]"
+               case rpc.ConnEventDebug:
+                       prefix = "[debug3]"
+               case rpc.ConnEventUpload:
+                       if level < safcm.LogInfo {
+                               return
+                       }
+                       prefix = "[info]"
+                       x.ConnEvent.Data = "remote helper upload in progress"
+               default:
+                       prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
+                       color = ColorRed
+               }
+               data = x.ConnEvent.Data
+       }
+
+       host := x.Host.Name()
+       if color != 0 {
+               host = ColorString(isTTY, color, host)
+       }
+       // Make sure to escape control characters to prevent terminal
+       // injection attacks
+       if !x.Escaped {
+               data = EscapeControlCharacters(isTTY, data)
+       }
+       log.Printf("%-9s [%s] %s", prefix, host, data)
+}