Write Logs to memory

What do you expect this code will print?

As in the main function I have written “log.Info(“Connected to the first DB connection”)”.So When I am printing the memlog in Init function then something should write into memlog

This is written before you change the log output in Init

So what change I have to make to write this log to memory?

Here is your program with the unused portions removed.

func Init() { // this is a normal function, it is called from Main
	var memLog bytes.Buffer
	log.AddHook(ContextHook{}) // this sets a context hook, it is never called
	log.SetOutput(&memLog) // this sets the output to memLog
	fmt.Println(memLog) // this prints the contents of memLog, maybe you want fmt.Println(memLog.String())
}

func main(){
	log.Info("Connected to the first DB connection") // this writes to logrus' default logger
	Init() // this changes the logger to memlog
        // then the program exits
}

When I am calling init function before log.Info in main function then hook is calling but nothing is writing to memlog.

This is the program you are executing, with all the unused code removed

func main() {
	log.Info("Connected to the first DB connection") // this writes to logrus' default logger
	var memLog bytes.Buffer
	log.SetOutput(&memLog) // this sets the output to memLog
	fmt.Println(memLog) // this prints the contents of memLog, maybe you want fmt.Println(memLog.String())
    // then the program exits
}

Does this make it clear why nothing is written to memLog?

I have used the same but nothing is printing with memlog as you can see in the attachment.

Nothing is printed because there are no log statements between setting the output to memLog and the program completing.

2 Likes

ok thanks.Can you tell me how can I read the logs in from memlogs at somewhere?

Thank you so much.Now its working and data writing to the memlogs

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