launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/worker/uniter/jujuc/juju-log.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuc
     5  
     6  import (
     7  	"fmt"
     8  	"launchpad.net/errgo/errors"
     9  	"strings"
    10  
    11  	"github.com/loggo/loggo"
    12  	"launchpad.net/gnuflag"
    13  
    14  	"launchpad.net/juju-core/cmd"
    15  )
    16  
    17  // JujuLogCommand implements the juju-log command.
    18  type JujuLogCommand struct {
    19  	cmd.CommandBase
    20  	ctx        Context
    21  	Message    string
    22  	Debug      bool
    23  	Level      string
    24  	formatFlag string // deprecated
    25  }
    26  
    27  func NewJujuLogCommand(ctx Context) cmd.Command {
    28  	return &JujuLogCommand{ctx: ctx}
    29  }
    30  
    31  func (c *JujuLogCommand) Info() *cmd.Info {
    32  	return &cmd.Info{
    33  		Name:    "juju-log",
    34  		Args:    "<message>",
    35  		Purpose: "write a message to the juju log",
    36  	}
    37  }
    38  
    39  func (c *JujuLogCommand) SetFlags(f *gnuflag.FlagSet) {
    40  	f.BoolVar(&c.Debug, "debug", false, "log at debug level")
    41  	f.StringVar(&c.Level, "l", "INFO", "Send log message at the given level")
    42  	f.StringVar(&c.Level, "log-level", "INFO", "")
    43  	f.StringVar(&c.formatFlag, "format", "", "deprecated format flag")
    44  }
    45  
    46  func (c *JujuLogCommand) Init(args []string) error {
    47  	if args == nil {
    48  		return errors.New("no message specified")
    49  	}
    50  	c.Message = strings.Join(args, " ")
    51  	return nil
    52  }
    53  
    54  func (c *JujuLogCommand) Run(ctx *cmd.Context) error {
    55  	if c.formatFlag != "" {
    56  		fmt.Fprintf(ctx.Stderr, "--format flag deprecated for command %q", c.Info().Name)
    57  	}
    58  	logger := loggo.GetLogger(fmt.Sprintf("unit.%s.juju-log", c.ctx.UnitName()))
    59  
    60  	logLevel := loggo.INFO
    61  	if c.Debug {
    62  		logLevel = loggo.DEBUG
    63  	} else if c.Level != "" {
    64  		var ok bool
    65  		logLevel, ok = loggo.ParseLevel(c.Level)
    66  		if !ok {
    67  			logger.Warningf("Specified log level of %q is not valid", c.Level)
    68  			logLevel = loggo.INFO
    69  		}
    70  	}
    71  
    72  	prefix := ""
    73  	if r, found := c.ctx.HookRelation(); found {
    74  		prefix = r.FakeId() + ": "
    75  	}
    76  
    77  	logger.Logf(logLevel, "%s%s", prefix, c.Message)
    78  	return nil
    79  }