Skip to content

Commit

Permalink
new: implemented log.Callback
Browse files Browse the repository at this point in the history
  • Loading branch information
evilsocket committed Dec 22, 2022
1 parent 753fbd3 commit 050951e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
3 changes: 3 additions & 0 deletions examples/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ func main() {
log.TimeFormat = "15:04:05"
log.DateTimeFormat = "2006-01-02 15:04:05"
log.Format = "{datetime} {level:color}{level:name}{reset} {message}"
log.Callback = func(verbosity log.Verbosity, message string) {
// fmt.Printf("got message '%s'\n", message)
}

if err := log.Open(); err != nil {
panic(err)
Expand Down
34 changes: 24 additions & 10 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/evilsocket/islazy/tui"
)

type MessageCallback = func(verbosity Verbosity, message string)

var (
// Level represents the current verbosity level of the logging system.
Level = INFO
Expand All @@ -19,6 +21,8 @@ var (
NoEffects = false
// OnFatal represents the callback/action to execute on Fatal messages.
OnFatal = ExitOnFatal
// A custom callback to execute for every log message.
Callback = dummyCallback

lock = &sync.Mutex{}
currMessage = ""
Expand Down Expand Up @@ -47,17 +51,27 @@ func Close() {
}
}

func emit(s string) {
func dummyCallback(verbosity Verbosity, message string) {

}

func removeEffects(s string) string {
for _, re := range reEffects {
s = re.ReplaceAllString(s, "")
}
return s
}

func emit(v Verbosity, s string) {
// remove all effects if found
plain := removeEffects(s)

Callback(v, plain)

if NoEffects {
for _, re := range reEffects {
s = re.ReplaceAllString(s, "")
}
s = plain
}

s = strings.Replace(s, "%", "%%", -1)
fmt.Fprintf(writer, s)
fmt.Fprintf(writer, "\n")
fmt.Fprintf(writer, "%s\n", s)
}

func do(v Verbosity, format string, args ...interface{}) {
Expand Down Expand Up @@ -87,7 +101,7 @@ func do(v Verbosity, format string, args ...interface{}) {
logLine += tui.RESET
}

emit(logLine)
emit(v, logLine)
}

// Raw emits a message without format to the logs.
Expand All @@ -96,7 +110,7 @@ func Raw(format string, args ...interface{}) {
defer lock.Unlock()

currMessage = fmt.Sprintf(format, args...)
emit(currMessage)
emit(INFO, currMessage)
}

// Debug emits a debug message.
Expand Down

0 comments on commit 050951e

Please sign in to comment.