github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/worker/logger/logger.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package logger 5 6 import ( 7 "github.com/juju/errors" 8 "github.com/juju/loggo" 9 10 "github.com/juju/juju/agent" 11 "github.com/juju/juju/api/logger" 12 "github.com/juju/juju/watcher" 13 "github.com/juju/juju/worker" 14 ) 15 16 var log = loggo.GetLogger("juju.worker.logger") 17 18 // Logger is responsible for updating the loggo configuration when the 19 // environment watcher tells the agent that the value has changed. 20 type Logger struct { 21 api *logger.State 22 agentConfig agent.Config 23 lastConfig string 24 } 25 26 // NewLogger returns a worker.Worker that uses the notify watcher returned 27 // from the setup. 28 func NewLogger(api *logger.State, agentConfig agent.Config) (worker.Worker, error) { 29 logger := &Logger{ 30 api: api, 31 agentConfig: agentConfig, 32 lastConfig: loggo.LoggerInfo(), 33 } 34 log.Debugf("initial log config: %q", logger.lastConfig) 35 w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{ 36 Handler: logger, 37 }) 38 if err != nil { 39 return nil, errors.Trace(err) 40 } 41 return w, nil 42 } 43 44 func (logger *Logger) setLogging() { 45 loggingConfig, err := logger.api.LoggingConfig(logger.agentConfig.Tag()) 46 if err != nil { 47 log.Errorf("%v", err) 48 } else { 49 if loggingConfig != logger.lastConfig { 50 log.Debugf("reconfiguring logging from %q to %q", logger.lastConfig, loggingConfig) 51 loggo.DefaultContext().ResetLoggerLevels() 52 if err := loggo.ConfigureLoggers(loggingConfig); err != nil { 53 // This shouldn't occur as the loggingConfig should be 54 // validated by the original Config before it gets here. 55 log.Warningf("configure loggers failed: %v", err) 56 // Try to reset to what we had before 57 loggo.ConfigureLoggers(logger.lastConfig) 58 } 59 logger.lastConfig = loggingConfig 60 } 61 } 62 } 63 64 func (logger *Logger) SetUp() (watcher.NotifyWatcher, error) { 65 log.Debugf("logger setup") 66 // We need to set this up initially as the NotifyWorker sucks up the first 67 // event. 68 logger.setLogging() 69 return logger.api.WatchLoggingConfig(logger.agentConfig.Tag()) 70 } 71 72 func (logger *Logger) Handle(_ <-chan struct{}) error { 73 logger.setLogging() 74 return nil 75 } 76 77 func (logger *Logger) TearDown() error { 78 // Nothing to cleanup, only state is the watcher 79 return nil 80 }