Provide a hook constructor which accepts an ETW provider

Previously, the only constructor for the etwlogrus hook accepted a name, and
created a new ETW provider with that name. With this change, there is another
constructor which takes an already created ETW provider. This is to allow the
use of the ETW provider for other things, such as if the application wants to
support ETW capture state.
This commit is contained in:
Kevin Parsons
2019-03-19 00:09:35 -07:00
parent ce5a3739bc
commit 811b34668c
+18 -8
View File
@@ -10,20 +10,25 @@ import (
// Hook is a Logrus hook which logs received events to ETW. // Hook is a Logrus hook which logs received events to ETW.
type Hook struct { type Hook struct {
provider *etw.Provider provider *etw.Provider
closeProvider bool
} }
// NewHook registers a new ETW provider and returns a hook to log from it. // NewHook registers a new ETW provider and returns a hook to log from it. The
// provider will be closed when the hook is closed.
func NewHook(providerName string) (*Hook, error) { func NewHook(providerName string) (*Hook, error) {
hook := Hook{}
provider, err := etw.NewProvider(providerName, nil) provider, err := etw.NewProvider(providerName, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
hook.provider = provider
return &hook, nil return &Hook{provider, true}, nil
}
// NewHookFromProvider creates a new hook based on an existing ETW provider. The
// provider will not be closed when the hook is closed.
func NewHookFromProvider(provider *etw.Provider) (*Hook, error) {
return &Hook{provider, false}, nil
} }
// Levels returns the set of levels that this hook wants to receive log entries // Levels returns the set of levels that this hook wants to receive log entries
@@ -186,7 +191,12 @@ func getFieldOpt(k string, v interface{}) etw.FieldOpt {
return etw.StringField(k, fmt.Sprintf("(Unsupported: %T) %v", v, v)) return etw.StringField(k, fmt.Sprintf("(Unsupported: %T) %v", v, v))
} }
// Close cleans up the hook and closes the ETW provider. // Close cleans up the hook and closes the ETW provider. If the provder was
// registered by etwlogrus, it will be closed as part of `Close`. If the
// provider was passed in, it will not be closed.
func (h *Hook) Close() error { func (h *Hook) Close() error {
return h.provider.Close() if h.closeProvider {
return h.provider.Close()
}
return nil
} }