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