Last active
July 15, 2016 23:02
-
-
Save ogryzek/cbc70198e29587b73591705ad389fcbc to your computer and use it in GitHub Desktop.
Messing around with writing logs to a file in Go (Golang)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// log_example.go | |
package main | |
import ( | |
"fmt" | |
mypackage "github.com/ogryzek/log_practice/mypackage" | |
"log" | |
"net/http" | |
"os" | |
) | |
func main() { | |
logFile, err := os.OpenFile("log.txt", os.O_WRONLY, 0666) | |
if err != nil { | |
fmt.Println("Here's your error message: ", err) | |
} | |
log.SetOutput(logFile) | |
defer logFile.Close() | |
http.HandleFunc("/", mypackage.Home) | |
http.HandleFunc("/time", mypackage.Time) | |
http.HandleFunc("/date", mypackage.Date) | |
http.ListenAndServe(":3000", nil) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// mypackage/mypackage.go | |
package mypackage | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
) | |
func Home(rw http.ResponseWriter, req *http.Request) { | |
fmt.Fprintln(rw, "Hello, and welcome. Available endpoints are:") | |
fmt.Fprintln(rw, "/time gives the current time") | |
fmt.Fprintln(rw, "/date give the current date") | |
message := fmt.Sprintf("%s: home endpoint hit.", time.Now()) | |
logStuff(message) | |
} | |
func Time(rw http.ResponseWriter, req *http.Request) { | |
t := time.Now() | |
message := fmt.Sprintf("The current time is: %s", t.Format("3:01")) | |
fmt.Fprintln(rw, message) | |
logStuff(message) | |
} | |
func Date(rw http.ResponseWriter, req *http.Request) { | |
currentTime := time.Now().Local() | |
message := fmt.Sprintf("Today's date is: %s", currentTime.Format("2006-01-01")) | |
fmt.Fprintln(rw, message) | |
logStuff(message) | |
} | |
func logStuff(message string) { | |
log.Println(message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment