My project consists of many files and many functions. I want to create a log file to know which functions are called. This log file will be of common for entire package.
I know how to create log file for one file but not for entire package.
code for single file:-
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("sam.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalln("failed")
}
log.SetOutput(file)
log.Println("this is log file")
log.Println("this is test\n")
add()
sub()
}
func add() {
log.Println("thi is add\n")
}
func sub() {
log.Println("thi is sub\n")
}
How to create log file common for project or folder or package.
The above code will add comments in a single line in file, I want them to be in entered in line by line.
logger := log.New(file, "my super logger: ", log.Lshortfile)
Now you can do logger.XXX. If you need this in other parts of the code, you have to pass logger variable as *log.Logger type. It would be also nice to close the log file before your program ends.
Would this method be safe in a REST server where you could have thousands of threads trying to write to the log file? ie: where would it buffer incoming attempts to write?
It will work with multiple go routines. The log packages uses a per log mutex so if one go routine is calling log.Println() the other stops until the mutex is unlocked.
// Output writes the output for a logging event. The string s contains
// the text to print after the prefix specified by the flags of the
// Logger. A newline is appended if the last character of s is not
// already a newline. Calldepth is used to recover the PC and is
// provided for generality, although at the moment on all pre-defined
// paths it will be 2.
func (l *Logger) Output(calldepth int, s string) error {
now := time.Now() // get this early.
var file string
var line int
l.mu.Lock()