Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding/removing handlers #86

Closed
audiolion opened this issue Aug 5, 2020 · 2 comments
Closed

adding/removing handlers #86

audiolion opened this issue Aug 5, 2020 · 2 comments

Comments

@audiolion
Copy link

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()
		}
	}
@tj
Copy link
Member

tj commented Aug 6, 2020

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,
}

@audiolion
Copy link
Author

ok cool! I think that will work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants