package log_test

import (
	"fmt"
	"net/http"

	"gitlab.com/gitlab-org/labkit/log"
)

func ExampleInitialize() {
	// Initialize the global logger
	closer, err := log.Initialize(
		log.WithFormatter("json"),    // Use JSON formatting
		log.WithLogLevel("info"),     // Use info level
		log.WithOutputName("stderr"), // Output to stderr
	)
	defer closer.Close()
	log.WithError(err).Info("This has been logged")

	// Example of configuring a non-global logger using labkit
	myLogger := log.New() // New logrus logger
	closer2, err := log.Initialize(
		log.WithLogger(myLogger),                  // Tell logkit to initialize myLogger
		log.WithFormatter("text"),                 // Use text formatting
		log.WithLogLevel("debug"),                 // Use debug level
		log.WithOutputName("/var/log/labkit.log"), // Output to `/var/log/labkit.log`
	)
	defer closer2.Close()

	log.WithError(err).Info("This has been logged")
}

func ExampleAccessLogger() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello world")
	})

	// This func is used by WithExtraFields to add additional fields to the logger
	extraFieldGenerator := func(r *http.Request) log.Fields {
		return log.Fields{"header": r.Header.Get("X-Magical-Header")}
	}

	http.ListenAndServe(":8080",
		log.AccessLogger(handler, // Add accesslogger middleware
			log.WithExtraFields(extraFieldGenerator),                          // Include custom fields into the logs
			log.WithFieldsExcluded(log.HTTPRequestReferrer|log.HTTPUserAgent), // Exclude user-agent and referrer fields from the logs
		),
	)
}
