func Connect() bool { success := false logrus.SetFormatter(&logrus.JSONFormatter{}) if !debugFlag { logrus.SetOutput(ioutil.Discard) } else { logrus.SetOutput(os.Stdout) } if fluentdServer != "" { host, port, err := net.SplitHostPort(fluentdServer) if err != nil { LogError(fmt.Sprintf("Unable to split to fluentd server [%s]!\n", fluentdServer), err.Error()) } portInt, err := strconv.Atoi(port) if err != nil { LogError(fmt.Sprintf("Unable to convert port format [%s]!\n", port), err.Error()) } hook := logrus_fluent.NewHook(host, portInt) LogStd(fmt.Sprintf("Received hook to fluentd server [%s]!\n", fluentdServer), false) logrus.AddHook(hook) success = true } return success }
func init() { var cfgFile string flag.StringVar(&cfgFile, "c", "myMon.cfg", "myMon configure file") flag.Parse() if _, err := os.Stat(cfgFile); err != nil { if os.IsNotExist(err) { log.WithField("cfg", cfgFile).Fatalf("myMon config file does not exists: %v", err) } } if err := cfg.readConf(cfgFile); err != nil { log.Fatalf("Read configure file failed: %v", err) } // Init log file log.SetFormatter(&log.JSONFormatter{}) log.SetLevel(log.Level(cfg.LogLevel)) if cfg.LogFile != "" { f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err == nil { log.SetOutput(f) return } } log.SetOutput(os.Stderr) }
func initLogrus(ctx *cli.Context) { logrus.SetFormatter(&logrus.TextFormatter{ TimestampFormat: time.RFC822, FullTimestamp: true, }) if level, err := logrus.ParseLevel(ctx.String("log_level")); err == nil { logrus.SetLevel(level) } else { log.Error(err) logrus.SetLevel(logrus.InfoLevel) } filename := ctx.String("log_file") logrus.SetOutput(os.Stderr) if filename != "" { var f *os.File _, err := os.Stat(filename) if !os.IsNotExist(err) { os.Rename(filename, filename+".prev") } f, err = os.Create(filename) if err != nil { log.Error("Cannot create log file ", err) log.Warning("Continuing to log to stderr") } else { logrus.SetOutput(f) } } }
func daemonEnvironmentSetup(c *cli.Context) error { var err error root := c.String("root") if root == "" { return fmt.Errorf("Have to specific root directory") } if err := util.MkdirIfNotExists(root); err != nil { return fmt.Errorf("Invalid root directory:", err) } lockPath := filepath.Join(root, LOCKFILE) if lockFile, err = util.LockFile(lockPath); err != nil { return fmt.Errorf("Failed to lock the file at %v: %v", lockPath, err.Error()) } logrus.SetLevel(logrus.DebugLevel) logName := c.String("log") if logName != "" { logFile, err := os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return err } logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.SetOutput(logFile) } else { logrus.SetOutput(os.Stdout) } return nil }
func main() { // Log as JSON instead of the default ASCII formatter. // log.SetFormatter(&log.JSONFormatter{}) // Use the Airbrake hook to report errors that have Error severity or above to // an exception tracker. You can create custom hooks, see the Hooks section. // log.AddHook(&logrus_airbrake.AirbrakeHook{}) setlogfile := false if setlogfile { // backendlog := logging.NewLogBackend(os.Stderr, "", 0) f, err := os.OpenFile("cdr-pusher.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(err.Error()) } defer f.Close() // Output to stderr instead of stdout, could also be a file. log.SetOutput(f) } else { log.SetOutput(os.Stderr) } // Only log the warning severity or above. // log.SetLevel(log.WarnLevel) log.SetLevel(log.InfoLevel) // log.SetLevel(log.DebugLevel) log.Info("StartTime: " + time.Now().Format("Mon Jan _2 2006 15:04:05")) RunApp() log.Info("StopTime: " + time.Now().Format("Mon Jan _2 2006 15:04:05")) }
func InitializeLogging(config *LoggingConfig, useStd bool, level string) { var lvl = log.DebugLevel var e error if level != "" { lvl, e = log.ParseLevel(level) } else if config.Level != "" { lvl, e = log.ParseLevel(config.Level) } if nil != e { lvl = log.DebugLevel } if useStd { log.SetOutput(os.Stdout) OUTPUT_FILE = nil } else { f, e := os.OpenFile(config.Filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if nil != e { fmt.Errorf("Open file <%s> for logging failed<%v>!\n", config.Filename, e) } else { log.SetOutput(f) OUTPUT_FILE = f } } if strings.ToLower(config.Format) == "json" { log.SetFormatter(&log.JSONFormatter{}) } else { log.SetFormatter(&PlainFormatter{}) } log.SetLevel(lvl) //log.Info("Logging Initialized.") }
func configureLogging(v *viper.Viper) { level, err := log.ParseLevel(v.GetString("log_level")) if err != nil { log.Fatalln(err) } log.SetLevel(level) if v.GetString("log_format") == "text" { log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true}) } else if v.GetString("log_format") == "json" { log.SetFormatter(&log.JSONFormatter{}) } else { log.Errorln("Error: log_type invalid, defaulting to text") log.SetFormatter(&log.TextFormatter{}) } switch v.GetString("log_target") { case "stdout": log.SetOutput(os.Stdout) case "stderr": log.SetOutput(os.Stderr) default: log.Errorln("Error: log_target invalid, defaulting to Stdout") log.SetOutput(os.Stdout) } }
func TestRunWithTimeoutFailed(t *testing.T) { log.SetLevel(log.DebugLevel) defer log.SetLevel(log.InfoLevel) tmp, _ := ioutil.TempFile("", "tmp") defer os.Remove(tmp.Name()) log.SetOutput(tmp) defer log.SetOutput(os.Stdout) cmd, _ := NewCommand("./testdata/test.sh failStuff --debug", "100ms") fields := log.Fields{"process": "test"} if err := RunWithTimeout(cmd, fields); err == nil { t.Errorf("Expected error but got nil") } time.Sleep(200 * time.Millisecond) buf, _ := ioutil.ReadFile(tmp.Name()) logs := string(buf) if strings.Contains(logs, "timeout after") { t.Fatalf("RunWithTimeout failed to cancel timeout after failure: %v", logs) } }
func Connect() bool { success := false logrus.SetFormatter(&logrus.JSONFormatter{}) if !debugFlag { logrus.SetOutput(ioutil.Discard) } else { logrus.SetOutput(os.Stdout) } if syslogServer != "" { hook, err := logrus_syslog.NewSyslogHook("tcp", syslogServer, syslog.LOG_INFO, "doppler") if err != nil { LogError(fmt.Sprintf("Unable to connect to syslog server [%s]!\n", syslogServer), err.Error()) } else { LogStd(fmt.Sprintf("Received hook to syslog server [%s]!\n", syslogServer), false) logrus.AddHook(hook) success = true } } return success }
func logAction(sl string) { if strings.HasPrefix(sl, "log on") { *logDump = "on" log.SetOutput(multi_writer) } else if strings.HasPrefix(sl, "log off") { *logDump = "off" log.SetOutput(os.Stderr) } else if strings.HasPrefix(sl, "log show") { // TODO: send all the saved log to websocket //h.broadcastSys <- []byte("{\"BufFlowDebug\" : \"" + *logDump + "\"}") } }
func Test_log_functions_panic_logger(t *testing.T) { a := assert.New(t) w := bytes.NewBuffer([]byte{}) log.SetOutput(w) defer log.SetOutput(os.Stderr) raisePanic() a.Contains(w.String(), "PANIC") a.Contains(w.String(), "raisePanic") a.Contains(w.String(), "Don't panic!") }
func InitLog(cfg *Cfg) { // Init log file log.SetFormatter(&log.JSONFormatter{}) log.SetLevel(log.Level(cfg.LogLevel)) if cfg.LogFile != "" { f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err == nil { log.SetOutput(f) return } } log.SetOutput(os.Stderr) }
// Test run callable with changed logging output func Test(callable func(*bytes.Buffer)) { buf := &bytes.Buffer{} logrus.SetOutput(buf) callable(buf) var loggerOut io.Writer if std.fd != nil { loggerOut = std.fd } else { loggerOut = os.Stderr } logrus.SetOutput(loggerOut) }
func parseConfig() *viper.Viper { if verbose { logrus.SetLevel(logrus.DebugLevel) logrus.SetOutput(os.Stderr) } // Get home directory for current user homeDir, err := homedir.Dir() if err != nil { fatalf("Cannot get current user home directory: %v", err) } if homeDir == "" { fatalf("Cannot get current user home directory") } // By default our trust directory (where keys are stored) is in ~/.notary/ mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir))) // If there was a commandline configFile set, we parse that. // If there wasn't we attempt to find it on the default location ~/.notary/config if configFile != "" { configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".") configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile)) configPath = filepath.Dir(configFile) } else { configPath = filepath.Join(homeDir, filepath.Dir(configDir)) } // Setup the configuration details into viper mainViper.SetConfigName(configFileName) mainViper.SetConfigType(configFileExt) mainViper.AddConfigPath(configPath) // Find and read the config file err = mainViper.ReadInConfig() if err != nil { logrus.Debugf("Configuration file not found, using defaults") // If we were passed in a configFile via -c, bail if it doesn't exist, // otherwise ignore it: we can use the defaults if configFile != "" || !os.IsNotExist(err) { fatalf("error opening config file %v", err) } } // At this point we either have the default value or the one set by the config. // Either way, the command-line flag has precedence and overwrites the value if trustDir != "" { mainViper.Set("trust_dir", trustDir) } // Expands all the possible ~/ that have been given, either through -d or config // If there is no error, use it, if not, attempt to use whatever the user gave us expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir")) if err == nil { mainViper.Set("trust_dir", expandedTrustDir) } logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir")) return mainViper }
func init() { log.SetFormatter(&log.TextFormatter{ FullTimestamp: true, TimestampFormat: "15:04:05", }) log.SetOutput(os.Stdout) }
func ConfigureLogging(level, format string, output io.Writer) error { switch level { case "debug": log.SetLevel(log.DebugLevel) case "info": log.SetLevel(log.InfoLevel) case "warn": log.SetLevel(log.WarnLevel) case "error": log.SetLevel(log.ErrorLevel) case "fatal": log.SetLevel(log.FatalLevel) case "panic": log.SetLevel(log.PanicLevel) default: return errors.New("Invalid log level: " + level) } switch format { case "text": log.SetFormatter(&log.TextFormatter{ TimestampFormat: time.RFC3339, FullTimestamp: true, }) case "json": log.SetFormatter(&log.JSONFormatter{ TimestampFormat: time.RFC3339, }) default: return errors.New("Invalid format type: " + format) } log.SetOutput(output) return nil }
//setLogger initializes logrus logger with some defaults func setLogger() { logrus.SetFormatter(&logrus.TextFormatter{}) logrus.SetOutput(os.Stderr) if gin.Mode() == gin.DebugMode { logrus.SetLevel(logrus.InfoLevel) } }
func init() { // Initialize Logging level to WARN // Need to change this to be configurable log.SetLevel(log.DebugLevel) ///log.SetLevel(log.WarnLevel) log.SetOutput(os.Stderr) }
func Action(c *cli.Context) { if len(c.Args()) != 1 { logrus.Fatalf("usage: gotty-client [GoTTY URL]") } // setting up logrus logrus.SetOutput(os.Stderr) if c.Bool("debug") { logrus.SetLevel(logrus.DebugLevel) } else { logrus.SetLevel(logrus.InfoLevel) } // create Client url := c.Args()[0] client, err := gottyclient.NewClient(url) if err != nil { logrus.Fatalf("Cannot create client: %v", err) } if c.Bool("skip-tls-verify") { client.SkipTLSVerify = true } // loop if err = client.Loop(); err != nil { logrus.Fatalf("Communication error: %v", err) } }
func init() { log.SetOutput(os.Stderr) log.SetLevel(log.InfoLevel) if os.Getenv("DEBUG") != "" { log.SetLevel(log.DebugLevel) } }
func main() { if reexec.Init() { return } // Set terminal emulation based on platform as required. stdin, stdout, stderr := term.StdStreams() logrus.SetOutput(stderr) flag.Merge(flag.CommandLine, clientFlags.FlagSet, commonFlags.FlagSet) flag.Usage = func() { fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]\n"+daemonUsage+" docker [ -h | --help | -v | --version ]\n\n") fmt.Fprint(os.Stdout, "A self-sufficient runtime for containers.\n\nOptions:\n") flag.CommandLine.SetOutput(os.Stdout) flag.PrintDefaults() help := "\nCommands:\n" for _, cmd := range dockerCommands { help += fmt.Sprintf(" %-10.10s%s\n", cmd.name, cmd.description) } help += "\nRun 'docker COMMAND --help' for more information on a command." fmt.Fprintf(os.Stdout, "%s\n", help) } flag.Parse() if *flVersion { showVersion() return } clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags) // TODO: remove once `-d` is retired handleGlobalDaemonFlag() if *flHelp { // if global flag --help is present, regardless of what other options and commands there are, // just print the usage. flag.Usage() return } c := cli.New(clientCli, daemonCli) if err := c.Run(flag.Args()...); err != nil { if sterr, ok := err.(cli.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(os.Stderr, sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
func SetEnv() { flag.Parse() if *debug { log.SetLevel(log.DebugLevel) } if *logFile != "" { if output, err := os.OpenFile(*logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil { log.Fatalf("Failed to log to file %s: %v", *logFile, err) } else { log.SetOutput(output) } } textFormatter := &log.TextFormatter{ FullTimestamp: true, } log.SetFormatter(textFormatter) if *catalogUrl == "" { err := "Halting Catalog service, Catalog github repo url not provided" log.Fatal(err) fmt.Errorf(err) } // Shutdown when parent dies if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGTERM), 0); err != 0 { log.Fatal("Failed to set parent death sinal, err") } }
//SetEnv parses the command line args and sets the necessary variables func SetEnv() { flag.Parse() if *debug { log.SetLevel(log.DebugLevel) } if *logFile != "" { if output, err := os.OpenFile(*logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil { log.Fatalf("Failed to log to file %s: %v", *logFile, err) } else { log.SetOutput(output) } } textFormatter := &log.TextFormatter{ FullTimestamp: true, } log.SetFormatter(textFormatter) if *catalogURL == "" { err := "Halting Catalog service, Catalog github repo url not provided" log.Fatal(err) _ = fmt.Errorf(err) } }
func (s *TestSuite) SetUpSuite(c *C) { logrus.SetLevel(logrus.DebugLevel) logrus.SetOutput(os.Stderr) var err error err = exec.Command("mkdir", "-p", devRoot).Run() c.Assert(err, IsNil) err = exec.Command("mkdir", "-p", devMount).Run() c.Assert(err, IsNil) // Prepare base image s.imageFile = filepath.Join(devRoot, imageFile) err = exec.Command("truncate", "-s", strconv.Itoa(volumeSize), s.imageFile).Run() c.Assert(err, IsNil) tmpDev, err := util.AttachLoopbackDevice(s.imageFile, false) c.Assert(err, IsNil) err = exec.Command("mkfs", "-t", "ext4", tmpDev).Run() c.Assert(err, IsNil) err = exec.Command("mount", tmpDev, devMount).Run() c.Assert(err, IsNil) err = exec.Command("touch", filepath.Join(devMount, imageTestFile)).Run() c.Assert(err, IsNil) err = exec.Command("umount", devMount).Run() c.Assert(err, IsNil) err = util.DetachLoopbackDevice(s.imageFile, tmpDev) c.Assert(err, IsNil) }
func init() { // Output to stderr instead of stdout log.SetOutput(os.Stderr) // Only log the Info severity or above. log.SetLevel(log.InfoLevel) }
func main() { flag.Parse() log.SetOutput(os.Stdout) log.SetLevel(log.DebugLevel) var client *docker.Client if os.Getenv("DOCKER_HOST") != "" { var err error certPath := os.Getenv("DOCKER_CERT_PATH") client, err = docker.NewTLSClient(os.Getenv("DOCKER_HOST"), path.Join(certPath, "cert.pem"), path.Join(certPath, "key.pem"), path.Join(certPath, "ca.pem")) if err != nil { log.Fatal(err) } } else { var err error client, err = docker.NewClient("unix:///var/run/docker.sock") if err != nil { log.Fatal(err) } } handler := Handler{docker: client, domain: fmt.Sprintf("%s.", *domain)} server := dns.Server{} server.Handler = &handler server.Net = *network server.Addr = *addr err := server.ListenAndServe() if err != nil { log.Fatal(err) } }
func main() { var ( debug bool historyDaysLimit int ) flag.Usage = usage flag.BoolVar(&debug, "debug", false, "Print debug information") flag.IntVar(&historyDaysLimit, "history-limit", 7, "History limit (in days)") flag.Parse() if len(flag.Args()) < 1 || historyDaysLimit < 1 { usage() os.Exit(1) } logrus.SetOutput(os.Stderr) if debug { logrus.SetLevel(logrus.DebugLevel) } api := slack.New(flag.Arg(0)) api.SetDebug(debug) newArriba(api.NewRTM(), historyDaysLimit).run() }
func init() { log.SetOutput(os.Stderr) log.SetLevel(log.DebugLevel) registry = openPackageRegistry("./packages.yml") log.Infof("Loaded %d NuGet package definitions.", len(registry.Packages)) }
func main() { f, err := os.OpenFile("server0.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666) if err != nil { fmt.Printf("error opening file: %v", err) } // don't forget to close it defer f.Close() log.SetOutput(f) log.SetLevel(log.DebugLevel) globalData, err := platform.CreateGlobalData() if err != nil { log.Fatal(err) return } runtime.GOMAXPROCS(runtime.NumCPU()) c, err := service.NewContester("server.ini", globalData) if err != nil { log.Fatal(err) return } rpc.Register(c) for { if err = rpc4go.ConnectServer(c.ServerAddress, rpc.DefaultServer); err != nil { log.Error(err) time.Sleep(time.Second * 5) } } }
func main() { runtime.GOMAXPROCS(1) log.SetLevel(log.DebugLevel) if logFile != "" { fo, logErr := os.Create(logFile) if logErr != nil { panic(logErr) } log.SetOutput(fo) } if frameNameRegex.FindString(frameworkName) != frameworkName { log.Fatal("Error, framework name not valid") } sched := scheduler.NewSchedulerCore( schedulerHostname, frameworkName, frameworkRole, []string{zookeeperAddr}, schedulerIPAddr, user, nodeCpus, nodeMem, nodeDisk, authProvider, mesosAuthPrincipal, mesosAuthSecretFile, useReservations) sched.Run(mesosMaster) }