Skip to content

Instantly share code, notes, and snippets.

@pravj
Last active May 29, 2016 17:16
Show Gist options
  • Save pravj/1a043a498f5e350a47ad252031a74276 to your computer and use it in GitHub Desktop.
Save pravj/1a043a498f5e350a47ad252031a74276 to your computer and use it in GitHub Desktop.
Sample application to demonstrate the working of "http.Handler" feature in "uber-go/zap".
// Author: Pravendra Singh (pravj)
// Reference: https://github.com/uber-go/zap/pull/71
// It can be viewed as an application which is trying to load its configurations initially.
// So the log level is `Debug` in starting. The application is emitting both `Info` and `Debug` messages.
// Once the config files are distributed perfectly (simulated by time.Sleep).
// It makes a http request using the provided `Handler` and the log level is changed to `Info`.
// After that the `Debug` messages are ignored.
package main
import (
"os"
"fmt"
"time"
"net/http"
"github.com/uber-go/zap"
)
func main() {
writeSyncer := zap.AddSync(os.Stderr)
logger := zap.NewJSON(
zap.Debug,
zap.Output(writeSyncer),
zap.ErrorOutput(writeSyncer),
)
go func() {
var i int
for i <= 4 {
logger.Debug(fmt.Sprintf("Debug - loading config - time left: %v", 5 - i))
logger.Info(fmt.Sprintf("Info - loading config - time left: %v", 5 - i))
time.Sleep(time.Millisecond * 1000)
i = i + 1
}
_, err := http.Get("http://localhost:3000/change")
if err != nil {
logger.Fatal("Error in GET request")
}
// intentionally leaving the check for response data
i = 1
for i <= 4 {
logger.Debug(fmt.Sprintf("Debug - loaded config - since: %v", i))
logger.Info(fmt.Sprintf("Info - loaded config - since: %v", i))
time.Sleep(time.Millisecond * 1000)
i = i + 1
}
os.Exit(0)
}()
hh := zap.NewHTTPHandler(logger)
mux := http.NewServeMux()
mux.Handle("/change", hh.ChangeLogLevel(zap.Info))
http.ListenAndServe(":3000", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment