Creating a log file for package


(ravuri sai ram akhil) #1

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")
}

  1. How to create log file common for project or folder or package.
  2. The above code will add comments in a single line in file, I want them to be in entered in line by line.

(Boban Acimovic) #2

file, err := os.OpenFile(“sam.txt”, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil { log.Fatalln(“failed”) }

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.