Created
March 10, 2013 06:14
-
-
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.
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
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) | |
} | |
} |
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.