Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a GoLang logger that allows logging in different formats to the console as well as a log file [closed]

Tags:

go

I come from a node.js background and am comfortable with a number of loggers (such as winston) that allow configurable formatted output to multiple sources such as the console as well as a log file, where the outputs to each may be formatted differently.

I am attempting to do something similar with GoLang and have had difficulty finding a logging package that supports this capability.

Is there a GoLang package that I could use to achieve this outcome?

like image 586
Eric Broda Avatar asked Jul 17 '16 23:07

Eric Broda


2 Answers

logrus is already mentioned here and it can give you exactly what you need using hooks. Hooks can send the log to different destinations, using different formats. You can find a list of hooks in the documentation like for sending logs to InfluxDB or Logstash. You can even implement your own hook based on your needs.

like image 122
Kaveh Shahbazian Avatar answered Oct 05 '22 11:10

Kaveh Shahbazian


Below is an example of achieving this with Sirupsen/logrus

package main

import (
  "github.com/Sirupsen/logrus"
  "os"
)

// Create a new instance of the logger. You can have any number of instances.
var log1 = logrus.New()
var log2 = logrus.New()

func main() {
  // The API for setting attributes is a little different than the package level
  // exported logger. See Godoc.
  log1.Out = os.Stderr
  log1.Formatter = &logrus.TextFormatter{}

  LogOutputFile, err := os.OpenFile("out.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
  if err != nil {
    logrus.Fatalf("error opening file: %v", err) 
  }  

  log2.Out = LogOutputFile
  log2.Formatter = &logrus.JSONFormatter{}

  log1.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")

  log2.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")

}
like image 20
Anuruddha Avatar answered Oct 05 '22 12:10

Anuruddha