Creating a log file for package


(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.


(Glenn Hancock) #3

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?


(akhil) #4
package logg

import (
	"log"
	"os"
)
func Loggi(s string) {
	file, err := os.OpenFile("mygo1.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer file.Close()
	if err != nil {
		log.Fatalln("failed")
	}
	log.SetOutput(file)
	log.Println(s)
}

This will not work if you create multiple threads but I am ok with it as I will create one thread at debugging.


(Johan Dahl) #5

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.

https://golang.org/src/log/log.go?s=9298:9328#L307

func Println(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
}

calls Output which uses mutex

https://golang.org/src/log/log.go?s=9298:9328#L143

// 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()

(system) closed #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.