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