func SetLogLevel(level string) error { resetLogLevel() switch level { case "trace": break case "debug": Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime) case "info": Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime) Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime) case "warning": Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime) Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime) Info = log.New(ioutil.Discard, "INF ", log.Ldate|log.Ltime) case "error": Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime) Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime) Info = log.New(ioutil.Discard, "INF ", log.Ldate|log.Ltime) Warning = log.New(ioutil.Discard, "WRN ", log.Ldate|log.Ltime) default: return errors.New(fmt.Sprintf("Invalid log level: %s", level)) } return nil }
func NewLogger(prefix string, level LogLevel) *Logger { godbc.Require(level >= 0, level) godbc.Require(level <= LEVEL_DEBUG, level) l := &Logger{} if level == LEVEL_NOLOG { l.level = LEVEL_DEBUG } else { l.level = level } l.critlog = log.New(stderr, prefix+" CRITICAL ", log.LstdFlags) l.errorlog = log.New(stderr, prefix+" ERROR ", log.LstdFlags) l.warninglog = log.New(stdout, prefix+" WARNING ", log.LstdFlags) l.infolog = log.New(stdout, prefix+" INFO ", log.LstdFlags) l.debuglog = log.New(stdout, prefix+" DEBUG ", log.LstdFlags) godbc.Ensure(l.critlog != nil) godbc.Ensure(l.errorlog != nil) godbc.Ensure(l.warninglog != nil) godbc.Ensure(l.infolog != nil) godbc.Ensure(l.debuglog != nil) return l }
func ErrLogOn(on bool) { if on { errlog = l.New(os.Stdout, "ERROR: starfish backend: ", l.Ldate|l.Ltime) } else { errlog = l.New(ioutil.Discard, "ERROR: starfish backend: ", l.Ldate|l.Ltime) } }
func (DS *MainSearch) initLogs(logdir string) { // open logs DS.logDir = logdir os.Mkdir(DS.logDir, os.ModePerm) tmpF0, err5 := os.Create(DS.logDir + "main:err.log") if err5 != nil { log.Fatal("couldn't create errs log", err5) } DS.errLogBuf = bufio.NewWriter(tmpF0) DS.errLogBuf.Flush() DS.errLog = log.New(DS.errLogBuf, "", log.LstdFlags) tmpF1, err1 := os.Create(DS.logDir + "main:main.log") if err1 != nil { log.Fatal("couldn't create main log", err1) } DS.mainLogBuf = bufio.NewWriter(tmpF1) DS.mainLogBuf.Flush() DS.mainLog = log.New(DS.mainLogBuf, "", log.LstdFlags) tmpF2, err2 := os.Create(DS.logDir + "main:eqns.log") if err2 != nil { log.Fatal("couldn't create eqns log", err2) } DS.eqnsLogBuf = bufio.NewWriter(tmpF2) DS.eqnsLogBuf.Flush() DS.eqnsLog = log.New(DS.eqnsLogBuf, "", log.LstdFlags) }
func (k *KLog) init() (err error) { if len(k.name) == 0 { return errors.New("not init.") } day := time.Now().Format("20060102") if k.day == day { return nil } k.Close() file := filepath.Clean(k.path + "/" + k.name + day + ".log") if !filepath.IsAbs(file) { file = filepath.Clean(ProcessPath() + "/" + file) } path := filepath.Dir(file) if err = os.MkdirAll(path, 0777); err != nil { return err } k.logFile, err = os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660) if err != nil { return err } if os.Stdout == nil || k.bstdout == false { k.log = log.New(k.logFile, k.prefix, log.Ldate|log.Ltime) } else { k.wr = io.MultiWriter(os.Stdout, k.logFile) k.log = log.New(k.wr, k.prefix, log.Ldate|log.Ltime) } k.day = day return nil }
func init() { flag.Parse() if *debug { logger = log.New(os.Stdout, "godev", log.LstdFlags) } else { logger = log.New(ioutil.Discard, "godev", log.LstdFlags) } goroot = runtime.GOROOT() + string(os.PathSeparator) dirs := build.Default.SrcDirs() for i := len(dirs) - 1; i >= 0; i-- { srcDir := dirs[i] if !strings.HasPrefix(srcDir, goroot) { srcDirs = append(srcDirs, srcDir) } if bundle_root_dir == "" { _, err := os.Stat(srcDir + "/github.com/sirnewton01/godev/bundles") if err == nil { bundle_root_dir = srcDir + "/github.com/sirnewton01/godev/bundles" break } } } // Try the location provided by the srcdir flag if bundle_root_dir == "" && *godev_src_dir != "" { _, err := os.Stat(*godev_src_dir + "/bundles") if err == nil { bundle_root_dir = *godev_src_dir + "/bundles" } } if bundle_root_dir == "" { log.Fatal("GOPATH variable doesn't contain the godev source.\nEither add the location to the godev source to your GOPATH or set the srcdir flag to the location.") } if os.Getenv("GOHOST") != "" { hostName = os.Getenv("GOHOST") certFile = os.Getenv("GOCERTFILE") keyFile = os.Getenv("GOKEYFILE") // If the host name is not loopback then we must use a secure connection // with certificatns if certFile == "" || keyFile == "" { log.Fatal("When using a public port a certificate file (GOCERTFILE) and key file (GOKEYFILE) environment variables must be provided to secure the connection.") } // Initialize the random magic key for this session rand.Seed(time.Now().UTC().UnixNano()) magicKey = strconv.FormatInt(rand.Int63(), 16) } }
func main() { // fmt.Printf("OAEP Encrypted [%s] to \n[%x]\n", string(plain_text), encrypted) // fmt.Printf("OAEP Decrypted [%x] to \n[%s]\n", encrypted, decrypted) //letters := []string{"a", "b", "c", "d"} //barrenoid.TestRsa() file, err := os.OpenFile("barrenslog.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) chkError(err) multi := io.MultiWriter(file, os.Stdout) dbgMsg = log.New(multi, "INFO: ", log.Ldate|log.Ltime) errMsg = log.New(multi, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) RoomList = make(map[string]*Room) var generalChatClients []*Client generalChatRoom := Room{"GeneralChat", generalChatClients} RoomList["GeneralChat"] = &generalChatRoom listener, err := net.Listen("tcp", PORT) chkError(err) dbgMsg.Println("Server started on port", PORT) //Main server loop, accept incoming connections for { conn, err := listener.Accept() chkError(err) dbgMsg.Println("Connection accepted from: ", conn.RemoteAddr()) go ClientHandler(conn) } }
func initLoggers() { logFatal = log.New(os.Stderr, "FATAL: ", log.Lshortfile) errorHandle := os.Stderr infoHandle := ioutil.Discard benchmarkHandle := ioutil.Discard if *logfile != "" { lgf, err := os.OpenFile(*logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { logFatal.Fatalf("Error opening log file (%s): %v\n", *logfile, err) } errorHandle = lgf infoHandle = lgf benchmarkHandle = lgf } if *benchmark != "" { prf, err := os.OpenFile(*benchmark, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { logFatal.Fatalf("Error opening benchmark file (%s): %v\n", *benchmark, err) } benchmarkHandle = prf } if *verbose { errorHandle = os.Stderr infoHandle = os.Stderr benchmarkHandle = os.Stderr } logError = log.New(errorHandle, "ERROR: ", log.Ldate|log.Lmicroseconds|log.Lshortfile) logInfo = log.New(infoHandle, "INFO: ", log.Ldate|log.Lmicroseconds) logBenchmark = log.New(benchmarkHandle, "BENCHMARK: ", log.Ldate|log.Lmicroseconds) }
/* Test Logger with a zero Byte Message, a corner case. This is merely to demonstrate the basics of log output when a logger is set for the connection. */ func TestLoggerMiscBytes0(t *testing.T) { ll := log.New(os.Stdout, "TLM01 ", log.Ldate|log.Lmicroseconds|log.Lshortfile) // Write phase n, _ := openConn(t) ch := check11(TEST_HEADERS) conn, _ := Connect(n, ch) conn.SetLogger(ll) // ms := "" // No data d := tdest("/queue/logger.zero.byte.msg") sh := Headers{HK_DESTINATION, d} e := conn.Send(sh, ms) if e != nil { t.Fatalf("Expected nil error, got [%v]\n", e) } // _ = conn.Disconnect(empty_headers) _ = closeConn(t, n) // Read phase n, _ = openConn(t) ch = check11(TEST_HEADERS) conn, _ = Connect(n, ch) ll = log.New(os.Stdout, "TLM02 ", log.Ldate|log.Lmicroseconds|log.Lshortfile) conn.SetLogger(ll) // sbh := sh.Add(HK_ID, d) sc, e := conn.Subscribe(sbh) if e != nil { t.Fatalf("Expected no subscribe error, got [%v]\n", e) } if sc == nil { t.Fatalf("Expected subscribe channel, got [nil]\n") } // Read MessageData var md MessageData select { case md = <-sc: case md = <-conn.MessageData: t.Fatalf("read channel error: expected [nil], got: [%v]\n", md.Message.Command) } if md.Error != nil { t.Fatalf("Expected no message data error, got [%v]\n", md.Error) } // The real tests here if len(md.Message.Body) != 0 { t.Fatalf("Expected body length 0, got [%v]\n", len(md.Message.Body)) } if string(md.Message.Body) != ms { t.Fatalf("Expected [%v], got [%v]\n", ms, string(md.Message.Body)) } // _ = conn.Disconnect(empty_headers) _ = closeConn(t, n) }
// Init function for generating the logging handlers func Init( traceHandle io.Writer, infoHandle io.Writer, debugHandle io.Writer, warningHandle io.Writer, errorHandle io.Writer) { Trace = log.New(traceHandle, "TRACE : ", log.Ldate|log.Ltime|log.Lshortfile) Info = log.New(infoHandle, "INFO : ", log.Ldate|log.Ltime|log.Lshortfile) Debug = log.New(debugHandle, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile) Warning = log.New(warningHandle, "WARN : ", log.Ldate|log.Ltime|log.Lshortfile) Error = log.New(errorHandle, "ERR : ", log.Ldate|log.Ltime|log.Lshortfile) }
// A read error whilst reading a fmt chunk should result in an error func TestFmtReadError(t *testing.T) { description := "A read error whilst reading a fmt chunk should result in an error" // Prepare a decoder to use var d decoder d.audio = new(audio.Audio) // Only log the chunk contents if verbose is enabled if testing.Verbose() { d.logger = log.New(os.Stdout, "", 0) } else { d.logger = log.New(ioutil.Discard, "", 0) } // Read an empty chunk to force a read error d.reader = bytes.NewReader([]byte{}) err := d.readFmtChunk() // Reading the chunk should have thrown an error if err == nil { t.Errorf("FAIL Test %v: %v:\nWant: error\nActual: nil", len(fmtChunkTests)+1, description) } else { t.Logf("PASS Test %v: %v:\nWant: error\nActual: %v", len(fmtChunkTests)+1, description, err.Error()) } }
func init() { c.ERROR = log.New(os.Stderr, "", log.LstdFlags) c.WARN = log.New(os.Stderr, "", log.LstdFlags) c.INFO = log.New(os.Stderr, "", log.LstdFlags) c.TRACE = log.New(os.Stderr, "", log.LstdFlags) }
func NewLogger(out io.Writer) *Logger { info := log.New(out, "INFO: ", log.Ldate|log.Ltime) warn := log.New(out, "WARN: ", log.Ldate|log.Ltime) alert := log.New(out, "ALERT: ", log.Ldate|log.Ltime|log.LUTC) return &Logger{info: info, warn: warn, alert: alert} }
func main() { verbose := false flag.BoolVar(&verbose, "v", false, "verbose logging") port := "3333" flag.StringVar(&port, "port", "3333", "port") host := "localhost" flag.StringVar(&host, "host", "localhost", "host") flag.Parse() logger := log.New(os.Stdin, "["+host+":"+port+"] ", log.LstdFlags) if !verbose { logger = log.New(new(NullWriter), "", 0) } server := server.New("http://"+host+":"+port, logger) logger.Printf("Starting") http.Handle("/", server.Handler()) err := http.ListenAndServe(host+":"+port, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
// Remember Exit(0) is success, Exit(1) is failure func main() { flag.Var(&slaveList, "control", "list of ip:port addresses to control") flag.Parse() if len(*testUrl) == 0 { flag.Usage() os.Exit(1) } if len(slaveList) > 0 && *listen != 0 { fmt.Fprintf(os.Stderr, "You can't have both --listen and --control flags") flag.Usage() os.Exit(1) } rand.Seed(time.Now().Unix()) // set up logging logWriter, err := os.OpenFile(*logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { println(err) os.Exit(1) } log.SetOutput(logWriter) TRACE = log.New(ioutil.Discard, "TRACE: ", log.Ldate|log.Ltime|log.Lshortfile) INFO = log.New(logWriter, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) ERROR = log.New(logWriter, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) INFO.Println("beginning run") os.Exit(realMain()) }
// NewLogger creates a new logger func NewLogger(stdout string, stderr string) (logger *Logger, err error) { var ( stderrWriter = os.Stderr stdoutWriter = os.Stdout toClose []closeable ) if stderr != "" { if stderrWriter, err = os.OpenFile(stderr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil { return } toClose = append(toClose, stderrWriter) } if stdout != "" { if stdoutWriter, err = os.OpenFile(stdout, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil { return } toClose = append(toClose, stderrWriter) } logger = &Logger{ stderr: log.New(stderrWriter, "ERROR ", log.LstdFlags|log.Lshortfile), stdout: log.New(stdoutWriter, "INFO ", log.LstdFlags|log.Lshortfile), toClose: toClose, } return }
// New ... func New(name string, host string, port uint16) (*Server, error) { // Create router router := http.NewServeMux() logPrefix := "[" + name + "] " // Create server s := &Server{ name: name, host: host, port: port, server: &http.Server{ Handler: router, ErrorLog: log.New(os.Stderr, logPrefix, 0), }, conns: make(connSet), statusLog: log.New(os.Stdout, logPrefix, 0), liveCSS: true, } // Handle JS router.HandleFunc("/livereload.js", jsHandler(s)) // Handle reload requests router.HandleFunc("/livereload", webSocketHandler(s)) return s, nil }
func TestInterruptLog(t *testing.T) { c := make(chan os.Signal, 1) server, l, err := createListener(killTime * 10) if err != nil { t.Fatal(err) } var buf bytes.Buffer var tbuf bytes.Buffer logger := log.New(&buf, "", 0) expected := log.New(&tbuf, "", 0) srv := &Server{Timeout: killTime, Server: server, Logger: logger, interrupt: c} go func() { srv.Serve(l) }() stop := srv.StopChan() c <- os.Interrupt expected.Print("shutdown initiated") <-stop if buf.String() != tbuf.String() { t.Fatal("shutdown log incorrect - got '" + buf.String() + "'") } }
func (g *gobuildMain) parseFlags() error { vlog := ioutil.Discard if g.flags.verbose { vlog = os.Stderr if g.flags.verboseFile != "" { verboseFile, err := os.Create(g.flags.verboseFile) if err != nil { return wraperr(err, "cannot create verbose file %s", g.flags.verboseFile) } vlog = verboseFile g.onClose = append(g.onClose, verboseFile.Close) } } g.verboseLog = log.New(vlog, "[gobuild-verbose]", log.LstdFlags|log.Lshortfile) g.errLog = log.New(os.Stderr, "[gobuild-err]", log.LstdFlags|log.Lshortfile) g.tc.verboseLog = g.verboseLog var err error g.storageDir, err = g.storageDirectory() if err != nil { return wraperr(err, "cannot create test storage directory") } g.testrunStorageDir, err = g.testReportDirectory() if err != nil { return wraperr(err, "cannot create test run storage directory") } g.verboseLog.Printf("Storing results to %s", g.storageDir) return nil }
// If /var/log/canopy files cannot be opened, then fallback to just logging to STDOUT func InitFallback() error { std.logger = log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile) std.errorLogger = log.New(os.Stdout, "ERROR ", log.LstdFlags|log.Lshortfile) std.warnLogger = log.New(os.Stdout, "WARN ", log.LstdFlags|log.Lshortfile) return nil }
func main() { //Revel Example //first set some color information info := gocolorize.NewColor("green") warning := gocolorize.NewColor("yellow") critical := gocolorize.NewColor("black+u:red") //We could also do this //critical.ToggleUnderline() //helper functions to shorten code i := info.Paint w := warning.Paint c := critical.Paint //Define the look/feel of the INFO logger INFO = log.New(os.Stdout, i("INFO "), log.Ldate|log.Lmicroseconds|log.Lshortfile) WARNING = log.New(os.Stdout, w("WARNING "), log.Ldate|log.Lmicroseconds|log.Lshortfile) CRITICAL = log.New(os.Stdout, c("CRITICAL")+" ", log.Ldate|log.Lmicroseconds|log.Lshortfile) //print out some messages, note the i wrappers for yellow text on the actual info string INFO.Println(i("Loaded module x")) INFO.Println(i("Loaded module y")) WARNING.Println(w("Failed to load module z")) e := MyError{What: "Failed"} CRITICAL.Println(c("Failed with an error code:", e)) }
func debugChanged() { if Debug { LogDebug = log.New(os.Stdout, "[Tango D] ", log.Ldate|log.Ltime) } else { LogDebug = log.New(ioutil.Discard, "", log.LstdFlags) } }
func initLoggers() { var writer io.Writer = ioutil.Discard var errWriter io.Writer = ioutil.Discard if Config.GetBool("log.enableStdOut") { writer = io.MultiWriter(writer, os.Stdout) } if Config.GetBool("log.enableStdErr") { errWriter = io.MultiWriter(errWriter, os.Stderr) } logFilePath := Config.GetString("log.filePath") if len(logFilePath) > 0 { if file, err := os.Open(logFilePath); err == nil { writer = io.MultiWriter(writer, file) errWriter = io.MultiWriter(errWriter, file) } } LogV = log.New(writer, "[VERBOSE]:", log.Ldate|log.Ltime|log.Lshortfile) LogD = log.New(writer, "[DEBUG]:", log.Ldate|log.Ltime|log.Lshortfile) LogE = log.New(errWriter, "[ERROR]:", log.Ldate|log.Ltime|log.Lshortfile) LogW = log.New(errWriter, "[WARNING]:", log.Ldate|log.Ltime|log.Lshortfile) //fmt.Printf("Log enable stdout: %v\n", Config.GetBool("log.enableStdOut")) //fmt.Printf("Log enable stderr: %v\n", Config.GetBool("log.enableStdErr")) }
func Load(tsdbChan chan<- *tsdb.Point) { var ( filePath = flag.String("f", "/etc/collect-statse/config", "configuration file") debugMode = flag.Bool("v", false, "verbose mode") testMode = flag.Bool("t", false, "configuration test") ) flag.Parse() log.SetFlags(0) if flag.NArg() != 0 { flag.Usage() os.Exit(1) } if *debugMode { w := os.Stderr xconfig.Debug = log.New(w, "debug: config: ", 0) statse.Debug = log.New(w, "debug: statse: ", 0) forwarder.Debug = log.New(w, "debug: forwarder: ", 0) filter.Debug = log.New(w, "debug: forwarder/filter: ", 0) aggregator.Debug = log.New(w, "debug: aggregator: ", 0) } config := new(Config) xconfig.Load(config, *filePath, "collect-statse?host={{.Hostname}}") if *testMode { config.Dump(os.Stdout) os.Exit(0) } Loaded = config aggregator.Init(tsdbChan) log.Printf("start pid=%d", os.Getpid()) }
// CreateLogger is a factory to instantiate a Logger struct. func CreateLogger( traceHandle io.Writer, infoHandle io.Writer, warningHandle io.Writer, errorHandle io.Writer) *Logger { var logger = new(Logger) logger.Trace = log.New(traceHandle, "TRACE: ", log.Ldate|log.Ltime|log.Lshortfile) logger.Info = log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) logger.Warning = log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile) logger.Error = log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) return logger }
func NewConsoleLogger(name string, w io.Writer) (cl *ConsoleLogger) { cl = &ConsoleLogger{ l: log.New(w, fmt.Sprintf("%s: ", name), log.LstdFlags), untransitioned: log.New(w, "fix-me: ", log.LstdFlags), } return }
func LogOn(on bool) { if on { log = l.New(os.Stdout, " LOG: starfish backend: ", l.Ldate|l.Ltime) } else { log = l.New(ioutil.Discard, " LOG: starfish backend: ", l.Ldate|l.Ltime) } }
func NewConsoleLogger(w io.Writer) (cl *ConsoleLogger) { cl = &ConsoleLogger{ l: log.New(w, "skynet: ", log.LstdFlags), untransitioned: log.New(w, "fix-me: ", log.LstdFlags), } return }
// LogInit initializes the various loggers. // func LogInit(trace, info, warning, error, panic io.Writer) { Trace = log.New(trace, "TRACE: ", log.LstdFlags|log.Lshortfile) Info = log.New(info, "INFO: ", log.LstdFlags) Warning = log.New(warning, "WARNING: ", log.LstdFlags|log.Lshortfile) Error = log.New(error, "ERROR: ", log.LstdFlags|log.Lshortfile) Panic = log.New(panic, "PANIC: ", log.LstdFlags|log.Lshortfile) }
func resetLogLevel() { Trace = log.New(os.Stdout, "TRC ", log.Ldate|log.Ltime) Debug = log.New(os.Stdout, "DBG ", log.Ldate|log.Ltime) Info = log.New(os.Stdout, "INF ", log.Ldate|log.Ltime) Warning = log.New(os.Stdout, "WRN ", log.Ldate|log.Ltime) Error = log.New(os.Stderr, "ERR ", log.Ldate|log.Ltime) }