Instagram
youtube
Facebook
  • 1 year, 6 months ago
  • 853 Views

Golang’s Logging Package (Default)

Yaman Birla
Table of Contents

In this tutorial we are going to learn how to create a log file using golang. Golang has a default log package that logs the message to the console as well as to the external file.

Golang has a default log package that logs the message to the console as well as to the external file. You can find more on this link

Below is the given code for using the default Golang log package:


package main

import "log"

func main() {

	log.Println("Hello, Yaman this side of the message!")
}

 


 

This prints:

 

Now, if you want to write these logs into a text file then see the below code with its output for understanding:


package main

import (
	"log"
	"os"
)

func main() {
	logFile, _ := os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer logFile.Close()
	log.SetOutput(logFile)
	log.Println("Hello, world! this is a message added to the newly created log file.")
}

This code created a file named log.txt in the Create and Append mode I run this code with the message “Hello, world!” only which is why it is showing this message first before the second one which I added after editing.

 


 

 

Although the default logger in golang is pretty straightforward to figure with, it doesn’t have all the specified options to be enclosed in an exceeding production system. It’s fine for a fast development/prototype, except for period eventualities, it barely ticks all the boxes. we might like logs that square measure additional structural and simple to browse. Meaning, with the logs thrown out by the system, we might basically get to reason them for easier identification and doubtless contain many additional fields and information.

 

The pros of using this default logging package in Golang are:

 

  • Very basic work.
  • Limited log levels. there are no thanks to reason messages into data, Warning, Fatal, Errors, and so on.
  • During exception, by exploitation of the Fatal or Panic ways, the appliance exits. there are no thanks to logging a mistake message while not quitting the appliance.
  • Primitive Message Formatting. it'd be higher if there have been ways to incorporate stack trace, format the date-time if required, add extra contexts, and so on.

Add a comment: