~rogpeppe/juju-core/azure

« back to all changes in this revision

Viewing changes to cmd/logging.go

  • Committer: William Reade
  • Date: 2012-01-20 21:32:53 UTC
  • mto: This revision was merged to the branch mainline in revision 47.
  • Revision ID: fwereade@gmail.com-20120120213253-csks5e12opl8t1rq
hefty rearrangement, few actual changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
// Copyright 2012, 2013 Canonical Ltd.
2
 
// Licensed under the AGPLv3, see LICENCE file for details.
3
 
 
4
 
package cmd
5
 
 
6
 
import (
7
 
        "io"
8
 
        "os"
9
 
 
10
 
        "launchpad.net/gnuflag"
11
 
        "launchpad.net/loggo"
12
 
)
13
 
 
14
 
// Log supplies the necessary functionality for Commands that wish to set up
15
 
// logging.
16
 
type Log struct {
17
 
        Path    string
18
 
        Verbose bool
19
 
        Debug   bool
20
 
        Config  string
21
 
}
22
 
 
23
 
// AddFlags adds appropriate flags to f.
24
 
func (l *Log) AddFlags(f *gnuflag.FlagSet) {
25
 
        f.StringVar(&l.Path, "log-file", "", "path to write log to")
26
 
        // TODO(thumper): rename verbose to --show-log
27
 
        f.BoolVar(&l.Verbose, "v", false, "if set, log additional messages")
28
 
        f.BoolVar(&l.Verbose, "verbose", false, "if set, log additional messages")
29
 
        f.BoolVar(&l.Debug, "debug", false, "if set, log debugging messages")
30
 
        f.StringVar(&l.Config, "log-config", "", "specify log levels for modules")
31
 
}
32
 
 
33
 
// Start starts logging using the given Context.
34
 
func (l *Log) Start(ctx *Context) (err error) {
35
 
        var target io.Writer
36
 
        if l.Path != "" {
37
 
                path := ctx.AbsPath(l.Path)
38
 
                target, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
39
 
                if err != nil {
40
 
                        return err
41
 
                }
42
 
        } else if l.Verbose || l.Debug {
43
 
                target = ctx.Stderr
44
 
        }
45
 
 
46
 
        if target != nil {
47
 
                writer := loggo.NewSimpleWriter(target, &loggo.DefaultFormatter{})
48
 
                _, err = loggo.ReplaceDefaultWriter(writer)
49
 
                if err != nil {
50
 
                        return err
51
 
                }
52
 
        } else {
53
 
                loggo.RemoveWriter("default")
54
 
        }
55
 
        if l.Verbose || l.Debug {
56
 
                level := loggo.INFO
57
 
                if l.Debug {
58
 
                        level = loggo.DEBUG
59
 
                }
60
 
                // Set the level on the root logger.
61
 
                loggo.GetLogger("").SetLogLevel(level)
62
 
        }
63
 
        loggo.ConfigureLoggers(l.Config)
64
 
        return nil
65
 
}