go-logging icon indicating copy to clipboard operation
go-logging copied to clipboard

Getting formatted logs in file and on cmd

Open gasparyanyur opened this issue 6 years ago • 1 comments

Hi all. In my go based application I have cmd part where user can follow the process. So I need to have 2 backand parts for loging -> cmd and file. So here is my code part

var file, _ = os.OpenFile("./access.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

	defer file.Close()

	var format = logging.MustStringFormatter(
		`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)

	backend1 := logging.NewLogBackend(file, "", 0)
	backend2 := logging.NewLogBackend(os.Stderr, "", 0)

	// For messages written to backend2 we want to add some additional
	// information to the output, including the used log level and the name of
	// the function.
	backend2Formatter := logging.NewBackendFormatter(backend2, format)

	// Only errors and more severe messages should be sent to backend1
	backend1Leveled := logging.AddModuleLevel(backend1)
	backend1Leveled.SetLevel(logging.ERROR, "")

	// Set the backends to be used.
	logging.SetBackend(backend1Leveled, backend2Formatter)

So on cmd I am getting formated log but in file only the error message. How can I solve this problem to get formated logs in both backands?

gasparyanyur avatar Feb 14 '19 13:02 gasparyanyur

The example shows how to do leveling and formatting, but not both together. To modify the example:

  1. Instantiate a backend1Formatter, the same as for backend2Formatter.
  2. When "leveling" backend1, give the new backend1formatter as an argument to AddModuleLevel().

The new example would like this:

var format = logging.MustStringFormatter(
	`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)

backend1 := logging.NewLogBackend(file, "", 0)
backend2 := logging.NewLogBackend(os.Stderr, "", 0)

// For messages written to backend2 we want to add some additional
// information to the output, including the used log level and the name of
// the function.
backend2Formatter := logging.NewBackendFormatter(backend2, format)

// Colors for backend1
backend1Formatter := logging.NewBackendFormatter(backend1, format)

// Only errors and more severe messages should be sent to backend1
backend1Leveled := logging.AddModuleLevel(backend1Formatter)
backend1Leveled.SetLevel(logging.ERROR, "")

// Set the backends to be used.
logging.SetBackend(backend1Leveled, backend2Formatter)

jl1 avatar Jun 08 '19 18:06 jl1