I have hundreds of subroutines writing into log file using log.Println()
I am using log.Println to write into error.log file.
func main() {
e, err := os.OpenFile("error.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("error opening file: %v", err)
os.Exit(1)
}
defer e.Close()
errLog := log.New(e, ">>>", log.Ldate|log.Ltime)
for i:=0; i<500; i++ {
go worker(errLog)
}
}
func worker(errLog log.Logger) {
// Do some work
errLog.Println("Hello world!!!")
}
Is my approach correct ? Or should I use channel to make sure only one process is logging into file at one time or is it taken care of inherently by log package?
Also does log package takes care of buffering or it directly writes into file?
To log to a file, you can use the OS package to create a log file if it does not exist or open and write to an existing file. Doing so will set the output of the log package to the specified output file. Keep in mind that the log package also supports other output destination that supports io.
The package log in Golang implements the simple logging package. It defines a type, Logger, with methods for formatting output. Golang Log will be helpful in the critical scenarios in real-time applications.
In this program, we will use log. Fatal() function to print specified message with timestamp on the console screen. The log. Fatal() is similar to the log. Print() function followed by a call to os.
From log.go:
func (l *Logger) Output(calldepth int, s string) error {
now := time.Now() // get this early.
var file string
var line int
l.mu.Lock()
defer l.mu.Unlock()
// ... Rest omitted
Since pretty much all package log
output functions go through Output
, and there's a mutex in Output
it's safe to say they're concurrency-safe.
I really can recommend reading the documentation:
A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.
See http://golang.org/pkg/log/#Logger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With