Cookie Consent by Free Privacy Policy Generator 📌 Insights Into Go Logging


✅ Insights Into Go Logging


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Logging is indeed very important when developing software applications, because logs help us to debug, monitor, and analyze our software applications. There are several go packages available for logging.

  1. log
  2. logrus
  3. zap
  4. zerolog
  5. glog

1. log

This is the logging package that comes with the standard Go Library. This has very basic logging capabilities. So, this package is good for logging in small applications.

Basic Logging

log.Print("Hello, log!")
log.Println("Hello with newline")
log.Printf("Hello, %s!", "formatted")
Output:
2024/04/28 11:28:37 Hello, log!
2024/04/28 11:28:37 Hello with newline
2024/04/28 11:28:37 Hello, formatted!

Log Prefix and Flags

The log package allows you to set a prefix to each log entry and control the logging format via flags.

log.SetPrefix("prefix: ")
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("This is a log with prefix-1")
log.Println("This is a log with prefix-2")
Output:
prefix: 2024/04/28 11:33:17 main.go:33: This is a log with prefix-1
prefix: 2024/04/28 11:33:17 main.go:34: This is a log with prefix-2

Levels of Severity

The log package doesn’t support log levels directly, but you can simulate them using different prefixes or by defining custom logging functions.

func info(args ...interface{}) {
   log.SetPrefix("INFO: ")
   log.Print(args...)
}


func error(args ...interface{}) {
   log.SetPrefix("ERROR: ")
   log.Print(args...)
}

Fatal and Panic Logging

log.Fatal* functions will log the message and then call os.Exit(1).
log.Panic* functions will log the message and then panic

log.Fatal("This is a fatal error")
log.Panic("This is a panic")

2. logrus

logrus is a powerful logging package which extends the capabilities of log package. logrus package can be used for logging in more complex applications. Some benefits of logrus are as below.

  1. Structured Logging: Logrus allows for logging in a structured format, particularly in JSON format.
  2. Log Levels: Logrus supports multiple logging levels (debug, info, warn, error, fatal, and panic), making it easy to output messages according to their severity.
  3. Hooks: You can add hooks to send logs to external systems or to trigger actions based on certain log messages.

Basic Logging

logrus.Info("This is an info message")
logrus.Warn("This is a warning message")
logrus.Error("This is an error message")
Output:
INFO[0000] This is an info message                      
WARN[0000] This is a warning message                    
ERRO[0000] This is an error message

Structured Logging

Use structured logging to include additional fields in the log entries.

logrus.WithFields(logrus.Fields{
       "username": "Sumudu Liyanage",
       "id":       123,
   }).Info("User logged in")
Output:
INFO[0000] User logged in id=123 username="Sumudu Liyanage"

Customizing Output

Logrus allows you to customize the output format. For instance, to log in JSON format.

logrus.SetFormatter(&logrus.JSONFormatter{})
   logrus.WithFields(logrus.Fields{
       "username": "Sumudu Liyanage",
       "id":       123,
   }).Info("User logged in")
Output:
{"id":123,"level":"info","msg":"User logged in","time":"2024-04-28T11:56:35+05:30","username":"Sumudu Liyanage"}

Hooks

You can add hooks to integrate with other systems. For example, adding a hook to send error-level logs to a monitoring service.

3. zap

zap is a high performance logging library. It's designed for applications that require fast, structured logging with minimal overhead. Choosing zap over logrus will be because of the speed.

logger, err := zap.NewProduction()
   if err != nil {
       panic(err)
   }


   logger.Info("This is an info message", zap.String("key", "value"), zap.Int("number", 1))
Output:
{"level":"info","ts":1714287036.2461052,"caller":"hello-world/main.go:14","msg":"This is an info message","key":"value","number":1}

4. zerolog

zerolog is another high-performance logging library for Go, specifically designed for zero-allocation JSON logging. zerolog minimizes memory allocations by writing JSON log events directly to output (like io.Writer), avoiding the overhead of temporary objects.

// Set global log level
   zerolog.SetGlobalLevel(zerolog.InfoLevel)


   // Configure zerolog to write to stdout with human-friendly formatting
   log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})


   // Logging with context
   log.Info().Str("role", "myrole").Msg("This is an info message")
   log.Debug().Int("id", 123).Msg("This is a debug message that won't be displayed")
   log.Error().Msg("This is an error message")
Output:
12:38PM INF This is an info message role=myrole
12:38PM ERR This is an error message

glog

glog offers a robust feature set for handling verbosity-based logging, which is quite useful for detailed control over log output granularity.

Unlike traditional log levels (info, warn, error), glog uses verbosity levels represented by integers. Higher numbers indicate more verbose logs, allowing developers to specify in great detail how much logging should be emitted.

/ Basic logging
   glog.Info("This is an informational message")
   glog.Warning("This is a warning message")
   glog.Error("This is an error message")


   // Conditional logging based on verbosity level
   if glog.V(2) {
       glog.Info("This is a verbose level 2 message")
   }

Is fmt also a log package?

The fmt package in Go (Golang) is not primarily a logging package but is used for formatting and printing output. It's part of the Go standard library and provides functions to format strings, numbers, and other data into strings and to print them to standard output (your console) or other outputs.

Thanks for reading!

...

✅ Insights Into Go Logging


📈 28.01 Punkte

✅ Microservices Logging | A Practical Guide to Logging in Microservices


📈 24.17 Punkte

✅ Power Apps- Logging With App Insights


📈 22.27 Punkte

✅ Insights into Why Hyperbola GNU/Linux is Turning into Hyperbola BSD


📈 21.66 Punkte

✅ Get started with Microsoft Viva Insights I Data-driven insights for business leaders


📈 20.37 Punkte

✅ Medium CVE-2022-1672: Insights from google pagespeed project Insights from google pagespeed


📈 20.37 Punkte

✅ Unveiling expert insights in our new podcast series: Apps, Games, & Insights


📈 20.37 Punkte

✅ Logging into multiple wm's with startx isn't working


📈 17.83 Punkte

✅ Apple Launches Single Sign-On Service To Make Logging Into TV Apps Less Time-Consuming


📈 17.83 Punkte

✅ How to autostart PWAs after logging into Windows


📈 17.83 Punkte

✅ Apple Launches Single Sign-On Service To Make Logging Into TV Apps Less Time-Consuming


📈 17.83 Punkte

✅ When Logging into Work Site My Camera LED Turns On


📈 17.83 Punkte

✅ Always use private browsing when logging into


📈 17.83 Punkte

✅ Optus Customers Saw Incorrect Info After Logging Into My Account Site


📈 17.83 Punkte

✅ Who’s logging into your Linux servers?


📈 17.83 Punkte

✅ Having trouble logging into Microsoft services? You're not alone.


📈 17.83 Punkte

✅ Avoid logging into Listmonk for Campaign Previews. Use this hack instead


📈 17.83 Punkte

✅ Having trouble logging into Microsoft services? You're not alone.


📈 17.83 Punkte

✅ Oops, Not sure what happened there when logging into Xbox Store


📈 17.83 Punkte

✅ Google started quietly logging you into Chrome with latest update, reports say


📈 17.83 Punkte

✅ How You Move Your Phone Can Reveal Insights Into Your Personality


📈 15.93 Punkte

✅ Navigating ADHD and Substance Use with Dr. Hanid Audish: Insights into Dangers and Preventive Measures


📈 15.93 Punkte

✅ Comprehensive Insights Into SDI in MySQL 8.0


📈 15.93 Punkte

✅ Gurucul federated search provides insights into data that is not centralized


📈 15.93 Punkte

✅ Insights into IR sniping and AI’s changing face of cyberthreats


📈 15.93 Punkte

✅ New! Better grouping of cases into topics in Dynamics 365 Customer Service Insights


📈 15.93 Punkte

✅ AI-Powered Insights into Molecular Evolution: From Codon Usage to Gene Expression in Natural Environments


📈 15.93 Punkte











matomo

Datei nicht gefunden!