Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 10, 2013 06:14
Show Gist options
  • Save physacco/5127345 to your computer and use it in GitHub Desktop.
Save physacco/5127345 to your computer and use it in GitHub Desktop.
This demonstrates usage of the log package in go. Log to stderr or a file.
package main
import (
"os"
"log"
"time"
)
func main() {
logfile, err := os.OpenFile("test.log",
os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
panic("failed to open log file")
}
defer logfile.Close()
log.SetOutput(logfile) // comment this then it'll write to stderr
for {
log.Println("this is a log") // > test.log
time.Sleep(5000 * time.Millisecond)
}
}
package main
import (
"os"
"log"
"time"
)
func main() {
logfile, err := os.OpenFile("test.log",
os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
panic("failed to open log file")
}
defer logfile.Close()
logger := log.New(logfile, "[test] ", log.LstdFlags)
for {
log.Println("this is a log") // > stderr
logger.Println("this is a log") // > test.log
time.Sleep(5000 * time.Millisecond)
}
}
@physacco
Copy link
Author

The log package uses a mutex to sync between goroutines so that it can be called from a large number of goroutines. It won't cause a "pthread_create failed" error. This is different from the fmt package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment