Beispiel #1
0
func newContext(fset *flag.FlagSet, args []string) (*context, *params, error) {
	p, err := parseArgs(fset, args)
	if err != nil {
		return nil, nil, err
	}
	if p.debug {
		loggo.ConfigureLoggers("DEBUG")
	}
	ctxt := &context{
		url:       p.url,
		method:    p.method,
		header:    make(http.Header),
		urlValues: make(url.Values),
		form:      make(url.Values),
		jsonObj:   make(map[string]interface{}),
	}
	for _, kv := range p.keyVals {
		if err := ctxt.addKeyVal(p, kv); err != nil {
			return nil, nil, err
		}
	}
	if p.useStdin && (len(ctxt.form) > 0 || len(ctxt.jsonObj) > 0) {
		return nil, nil, errors.New("cannot read body from stdin when form or JSON body is specified")
	}
	if p.basicAuth != "" {
		ctxt.header.Set("Authorization",
			"Basic "+base64.StdEncoding.EncodeToString([]byte(p.basicAuth)))
	}
	if p.json {
		ctxt.header.Set("Content-Type", "application/json")
	}
	return ctxt, p, nil
}
Beispiel #2
0
func (t *LoggingSuite) setUp(c *gc.C) {
	if _, ok := loggo.ParseLevel(*logConfig); ok {
		*logConfig = "<root>=" + *logConfig
	}
	err := loggo.ConfigureLoggers(*logConfig)
	c.Assert(err, gc.IsNil)
}
Beispiel #3
0
func main() {
	args := os.Args
	if len(args) > 1 {
		loggo.ConfigureLoggers(args[1])
	} else {
		fmt.Println("Add a parameter to configure the logging:")
		fmt.Println("E.g. \"<root>=INFO;first=TRACE\"")
	}
	fmt.Println("\nCurrent logging levels:")
	fmt.Println(loggo.LoggerInfo())
	fmt.Println("")

	rootLogger.Infof("Start of test.")

	FirstCritical("first critical")
	FirstError("first error")
	FirstWarning("first warning")
	FirstInfo("first info")
	FirstDebug("first debug")
	FirstTrace("first trace")

	loggo.ReplaceDefaultWriter(loggo.NewSimpleWriter(os.Stderr, &loggo.ColorFormatter{}))

	SecondCritical("second critical")
	SecondError("second error")
	SecondWarning("second warning")
	SecondInfo("second info")
	SecondDebug("second debug")
	SecondTrace("second trace")

}
Beispiel #4
0
func (s *GlobalSuite) TestConfigureLoggers(c *gc.C) {
	err := loggo.ConfigureLoggers("testing.module=debug")
	c.Assert(err, gc.IsNil)
	expected := "<root>=WARNING;testing.module=DEBUG"
	c.Assert(loggo.DefaultContext().Config().String(), gc.Equals, expected)
	c.Assert(loggo.LoggerInfo(), gc.Equals, expected)
}
Beispiel #5
0
func (s *LoggingSuite) setUp(c *gc.C) {
	loggo.ResetWriters()
	loggo.ReplaceDefaultWriter(&gocheckWriter{c})
	loggo.ResetLoggers()
	err := loggo.ConfigureLoggers(logConfig)
	c.Assert(err, gc.IsNil)
}
Beispiel #6
0
func main() {
	args := os.Args
	if len(args) > 1 {
		loggo.ConfigureLoggers(args[1])
	} else {
		fmt.Println("Add a parameter to configure the logging:")
		fmt.Println("E.g. \"<root>=INFO;first=TRACE\"")
	}
	fmt.Println("\nCurrent logging levels:")
	fmt.Println(loggo.LoggerInfo())
	fmt.Println("")

	rootLogger.Infof("Start of test.")

	FirstCritical("first critical")
	FirstError("first error")
	FirstWarning("first warning")
	FirstInfo("first info")
	FirstTrace("first trace")

	SecondCritical("first critical")
	SecondError("first error")
	SecondWarning("first warning")
	SecondInfo("first info")
	SecondTrace("first trace")

}
Beispiel #7
0
// setupLogging initializes the global logging parameters.
// Log levels can be overriden using the LEMONCRYPT_LOGGING environment variable.
func setupLogging() {
	config := os.Getenv("LEMONCRYPT_LOGGING")
	if config == "" {
		config = "<root>=DEBUG"
	}
	loggo.ConfigureLoggers(config)
	logger.Tracef("logging set up")
}
Beispiel #8
0
func init() {
	// If the environment key is empty, ConfigureLoggers returns nil and does
	// nothing.
	err := loggo.ConfigureLoggers(os.Getenv(osenv.JujuStartupLoggingConfigEnvKey))
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR parsing %s: %s\n\n", osenv.JujuStartupLoggingConfigEnvKey, err)
	}
}
Beispiel #9
0
func (logger *Logger) setLogging() {
	loggingConfig, err := logger.api.LoggingConfig(logger.agentConfig.Tag())
	if err != nil {
		log.Errorf("%v", err)
	} else {
		if loggingConfig != logger.lastConfig {
			log.Debugf("reconfiguring logging from %q to %q", logger.lastConfig, loggingConfig)
			loggo.ResetLoggers()
			if err := loggo.ConfigureLoggers(loggingConfig); err != nil {
				// This shouldn't occur as the loggingConfig should be
				// validated by the original Config before it gets here.
				log.Warningf("configure loggers failed: %v", err)
				// Try to reset to what we had before
				loggo.ConfigureLoggers(logger.lastConfig)
			}
			logger.lastConfig = loggingConfig
		}
	}
}
Beispiel #10
0
func (s *LoggingSuite) setUp(c *gc.C) {
	loggo.ResetLogging()
	// Don't use the default writer for the test logging, which
	// means we can still get logging output from tests that
	// replace the default writer.
	loggo.RegisterWriter(loggo.DefaultWriterName, discardWriter{})
	loggo.RegisterWriter("loggingsuite", &gocheckWriter{c})
	err := loggo.ConfigureLoggers(logConfig)
	c.Assert(err, gc.IsNil)
}
Beispiel #11
0
// Start starts logging using the given Context.
func (log *Log) Start(ctx *Context) error {
	if log.Verbose && log.Quiet {
		return fmt.Errorf(`"verbose" and "quiet" flags clash, please use one or the other, not both`)
	}
	ctx.quiet = log.Quiet
	ctx.verbose = log.Verbose
	if log.Path != "" {
		path := ctx.AbsPath(log.Path)
		target, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
		if err != nil {
			return err
		}
		writer := log.GetLogWriter(target)
		err = loggo.RegisterWriter("logfile", writer)
		if err != nil {
			return err
		}
	}
	level := loggo.WARNING
	if log.ShowLog {
		level = loggo.INFO
	}
	if log.Debug {
		log.ShowLog = true
		level = loggo.DEBUG
		// override quiet or verbose if set, this way all the information goes
		// to the log file.
		ctx.quiet = true
		ctx.verbose = false
	}

	if log.ShowLog {
		// We replace the default writer to use ctx.Stderr rather than os.Stderr.
		writer := log.GetLogWriter(ctx.Stderr)
		_, err := loggo.ReplaceDefaultWriter(writer)
		if err != nil {
			return err
		}
	} else {
		loggo.RemoveWriter("default")
		// Create a simple writer that doesn't show filenames, or timestamps,
		// and only shows warning or above.
		writer := NewWarningWriter(ctx.Stderr)
		err := loggo.RegisterWriter("warning", writer)
		if err != nil {
			return err
		}
	}
	// Set the level on the root logger.
	root := loggo.GetLogger("")
	root.SetLogLevel(level)
	// Override the logging config with specified logging config.
	loggo.ConfigureLoggers(log.Config)
	return nil
}
Beispiel #12
0
func (*loggerSuite) TestConfigureLoggers(c *gc.C) {
	for i, test := range configureLoggersTests {
		c.Logf("test %d: %q", i, test.spec)
		loggo.ResetLoggers()
		err := loggo.ConfigureLoggers(test.spec)
		c.Check(loggo.LoggerInfo(), gc.Equals, test.info)
		if test.err != "" {
			c.Assert(err, gc.ErrorMatches, test.err)
			continue
		}
		c.Assert(err, gc.IsNil)

		// Test that it's idempotent.
		err = loggo.ConfigureLoggers(test.spec)
		c.Assert(err, gc.IsNil)
		c.Assert(loggo.LoggerInfo(), gc.Equals, test.info)

		// Test that calling ConfigureLoggers with the
		// output of LoggerInfo works too.
		err = loggo.ConfigureLoggers(test.info)
		c.Assert(err, gc.IsNil)
		c.Assert(loggo.LoggerInfo(), gc.Equals, test.info)
	}
}
Beispiel #13
0
func (s *LoggerSuite) TestInitialState(c *gc.C) {
	config, err := s.State.EnvironConfig()
	c.Assert(err, jc.ErrorIsNil)
	expected := config.LoggingConfig()

	initial := "<root>=DEBUG;wibble=ERROR"
	c.Assert(expected, gc.Not(gc.Equals), initial)

	loggo.ResetLoggers()
	err = loggo.ConfigureLoggers(initial)
	c.Assert(err, jc.ErrorIsNil)

	loggingWorker, _ := s.makeLogger(c)
	defer worker.Stop(loggingWorker)

	s.waitLoggingInfo(c, expected)
}
Beispiel #14
0
func setupLogger() {
	fmt.Println("Setting up logger")
	loggo.ConfigureLoggers("<root>=TRACE")
	oldWriter, _, err := loggo.RemoveWriter("default")
	// err is non-nil if and only if the name isn't found.
	loggo.RegisterWriter("default", oldWriter, loggo.TRACE)
	fmt.Println("Log file: " + viper.GetString("Filename"))

	writer := &lumberjack.Logger{
		Filename:   viper.GetString("Filename"),
		MaxSize:    viper.GetInt("MaxSize"), // megabytes
		MaxBackups: viper.GetInt("MaxBackups"),
		MaxAge:     viper.GetInt("MaxAge"), // days
	}

	newWriter := loggo.NewSimpleWriter(writer, &ClientLogFormatter{})
	err = loggo.RegisterWriter("testfile", newWriter, loggo.TRACE)

	if err != nil {
		fmt.Println("Error registering logger")
	}
}
Beispiel #15
0
func (*auditSuite) SetUpTest(c *gc.C) {
	loggo.ResetLoggers()
	loggo.ResetWriters()
	err := loggo.ConfigureLoggers(`<root>=ERROR; audit=INFO`)
	c.Assert(err, jc.ErrorIsNil)
}
Beispiel #16
0
func main() {
	args := os.Args
	if len(args) > 1 {
		loggo.ConfigureLoggers(args[1])
	} else {
		fmt.Println("Add a parameter to configure the logging:")
		fmt.Println("E.g. \"<root>=INFO;first=TRACE\"")
	}
	fmt.Println("\nCurrent logging levels:")
	fmt.Println(loggo.LoggerInfo())
	fmt.Println("")

	rootLogger.Infof("Start of test.")

	FirstCritical("first critical")
	FirstError("first error")
	FirstWarning("first warning")
	FirstInfo("first info")
	FirstTrace("first trace")

	SecondCritical("first critical")
	SecondError("first error")
	SecondWarning("first warning")
	SecondInfo("first info")
	SecondTrace("first trace")

	writer, err := rfw.Open("./myprogram", 0644)
	if err != nil {
		log.Fatalln("Could not open '/var/log/myprogram': ", err)
	}

	log := log.New(writer, "[myprogram] ", log.LstdFlags)
	log.Println("Logging as normal")

	//defaultWriter, _, err := loggo.RemoveWriter("default")

	// err is non-nil if and only if the name isn't found.
	//loggo.RegisterWriter("default", writer, loggo.TRACE)
	newWriter := loggo.NewSimpleWriter(writer, &loggo.DefaultFormatter{})
	err = loggo.RegisterWriter("testfile", newWriter, loggo.TRACE)

	now := time.Now().Nanosecond()
	fmt.Printf("CurrentTime: %d\n", now)
	FirstCritical("first critical")
	FirstError("first error")
	FirstWarning("first warning")
	FirstInfo("first info")
	FirstTrace("first trace")

	SecondCritical("first critical")
	SecondError("first error")
	SecondWarning("first warning")
	SecondInfo("first info")
	SecondTrace("first trace")

	viper.SetConfigName("config")        // name of config file (without extension)
	viper.AddConfigPath("/etc/appname/") // path to look for the config file in
	viper.AddConfigPath("$HOME/")        // call multiple times to add many search paths
	viper.ReadInConfig()                 // Find and read the config file

	title := viper.GetString("title")
	fmt.Printf("TITLE=%s\n", title)
}