apex / log

Structured logging package for Go.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

adding/removing handlers

audiolion opened this issue · comments

I am using the apex logs handler, but also a few other handlers, os.Stdout in development, and the json handler writing to a local log file. I have a scenario where when I am exiting my program I want to close the file that json writes to. This could error though, and I want to send that error to the apex logs handler, but I don't want to retry writing that log to the file that failed to close. Is there a way that I could remove the file handler after the error occurs and before I write to apex?

        handlers := []apex.Handler{json.New(file)}

	var apexHandler *apexlogs.Handler
	if opts.ApexURL != "" && opts.ApexProjectID != "" && opts.ApexAuthToken != "" {
		apexHandler = apexlogs.New(opts.ApexURL, opts.ApexProjectID, opts.ApexAuthToken)
		handlers = append(handlers, apexHandler)
	}

	if opts.IsDev {
		handlers = append(handlers, text.New(os.Stdout))
        }
        apex.SetHandler(multi.New(handlers...))

	logger = apex.WithFields(versionLogFields()).WithFields(hostInfoLogFields())

	cleanup = func() {
		if err := file.Close(); err != nil {
                        // Should I call apex.SetHandler(..) here to remove the json handler?
			logger.WithError(err).Error("log file failed to close")
		}
		if apexHandler != nil {
			apexHandler.Close()
		}
	}

Hmm currently SetHandler() isn't thread-safe, it sort of assumes you set it once and forget, but it should be fine in this case if you're closing things down.

You could also create a separate log.Logger{} instance to avoid that entirely:

log.Logger{
  Handler: apexstuff,
  Level: log.InfoLevel,
}

ok cool! I think that will work.