// Capture creates a new *Logger instance with an internal buffer. The prefix // and flags default to the values of log.Prefix() and log.Flags(), respectively. // This function is meant to be called from test code. See the godoc for the // Logger struct for details. func Capture() *Logger { out := new(bytes.Buffer) return &Logger{ Log: out, Logger: log.New(out, log.Prefix(), log.Flags()), } }
func main() { r := Rectangle{length: 5, width: 3} fmt.Println("Rectangle r details are: ", r) fmt.Println("Rectangle r's area is: ", r.Area()) s := Shaper(r) fmt.Println("Area of the Shape r is: ", s.Area()) fmt.Println("Area of the Shape r is: ", s.Shit()) return cfgFile := "file.txt" f, err := os.OpenFile(cfgFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) // For read access. if err != nil { checkError(err) } // var l int myLog := log.New(f, "PREFIXIO ", log.Lshortfile|log.Ldate|log.Ltime) // l, err = f.WriteString("HELLO THERE n"); // fmt.Printf("length is :%d\n", l); if err != nil { checkError2(err) } myLog.Println("from logger") //myFileAppendLine(cfgFile, "HELLO THERE \n"); fmt.Printf("Flags:%q Prefix:%q\n", log.Flags(), log.Prefix()) os.Exit(0) }
// Prefix -> log.Prefix func (this *Logger) Prefix() string { if this == nil { return log.Prefix() } this.Calls++ return this.Logger.Prefix() }
func (s *MainSuite) Test_initLog_SetsLogFlagsIfDebugging(c *C) { log.SetFlags(0) *config.DebugFlag = true initLog() c.Assert(log.Flags(), Equals, log.Ldate|log.Ltime|log.Llongfile) c.Assert(log.Prefix(), Equals, "[CoyIM] ") }
func logMsg(level string, L *lua.LState) int { old := log.Prefix() log.SetPrefix(level) tpl := L.CheckString(1) top := L.GetTop() // Optimization for the case where no formatter needs to be // applied. if top <= 1 { log.Print(tpl) log.SetPrefix(old) return 0 } args := make([]interface{}, top-1) for i := 2; i <= top; i++ { args[i-2] = L.Get(i) } // FIXME: If more args are supplied than placeholders, this will // generate an error. log.Printf(tpl, args...) log.SetPrefix(old) return 0 }
func TestBeforeNotifyPanic(t *testing.T) { stack := middlewareStack{} stack.OnBeforeNotify(func(e *Event, c *Configuration) error { panic("oops") }) called := false b := &bytes.Buffer{} stack.Run(nil, &Configuration{Logger: log.New(b, log.Prefix(), 0)}, func() error { called = true return nil }) logged := b.String() if logged != "bugsnag/middleware: unexpected panic: oops\n" { t.Errorf("Logged: %s", logged) } if called == false { t.Errorf("Notify was not called when BeforeNotify panicked") } }
func init() { // Set up builtin middlewarez OnBeforeNotify(httpRequestMiddleware) // Default configuration Config.update(&Configuration{ APIKey: "", Endpoint: "https://notify.bugsnag.com/", Hostname: "", AppVersion: "", ReleaseStage: "", ParamsFilters: []string{"password", "secret"}, // * for app-engine ProjectPackages: []string{"main*"}, NotifyReleaseStages: nil, Logger: log.New(os.Stdout, log.Prefix(), log.Flags()), PanicHandler: defaultPanicHandler, Transport: http.DefaultTransport, }) hostname, err := os.Hostname() if err == nil { Config.Hostname = hostname } }
// Register sets CoLog as output for the default logger. // It "hijacks" the standard logger flags and prefix previously set. // It's not possible to know the output previously set, so the // default os.Stderr is assumed. func Register() { // Inherit standard logger flags and prefix if appropriate if !std.customFmt { std.formatter.SetFlags(log.Flags()) } if log.Prefix() != "" && std.prefix == "" { std.SetPrefix(log.Prefix()) } // Disable all extras log.SetPrefix("") log.SetFlags(0) // Set CoLog as output log.SetOutput(std) }
// print log in console, default log string wont be print in console // NOTICE: when console is on, the process will really slowly func (f *FileLogger) pc(str string) { if f.logConsole { if log.Prefix() != f.prefix { log.SetPrefix(f.prefix) } log.Println(str) } }
func NewWebServer(webCfg *WebConfig, sessionService services.SessionService) framework.WebServer { sessionManager := NewSessionManager(webCfg, sessionService) _srv := _web.NewServer() _srv.Logger = log.New(ioutil.Discard, log.Prefix(), log.Flags()) server := &webServer{config: webCfg, sessionManager: sessionManager, _srv: _srv} return server }
// Logf logs a message to one or more loggers and uses a format string. func (cxt *ExecutionContext) Logf(prefix string, format string, v ...interface{}) { if _, ok := cxt.skiplist[prefix]; ok { return } tmpPrefix := log.Prefix() log.SetPrefix(prefix) log.Printf(format, v...) log.SetPrefix(tmpPrefix) }
func logMsg(format, msg string, a ...interface{}) { defer log.SetFlags(log.Flags()) defer log.SetPrefix(log.Prefix()) log.SetFlags(0) log.SetPrefix("") msg = fmt.Sprintf(format+"\n", msg) log.Printf(msg, a...) }
func exportCommand(env Env, args []string) (err error) { defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "export:") log_debug("start") context := ExportContext{env: env} var target string if len(args) > 1 { target = args[1] } shell := DetectShell(target) if shell == nil { return fmt.Errorf("Unknown target shell '%s'", target) } log_debug("load config") if err = context.loadConfig(); err != nil { return } log_debug("loading RCs") if context.getRCs(); !context.hasRC() { return nil } log_debug("updating RC") if err = context.updateRC(); err != nil { log_debug("err: %v", err) context.resetEnv() } if context.newEnv == nil { log_debug("newEnv nil, exiting") return nil } diffString := context.diffString(shell) log_debug("env diff %s", diffString) fmt.Print(diffString) return }
// Printf calls Printf only if the level is equal or lower than the set level. // If the level is FatalLevel, it will call Fatalf regardless... func Printf(l Level, format string, v ...interface{}) { if l == FatalLevel { stdLog.Fatalf(format, v...) return } if l <= level { defer stdLog.SetPrefix(stdLog.Prefix()) stdLog.SetPrefix(levelPrefix[l]) stdLog.Printf(format, v...) } }
// Print calls Print only if the level is equal or lower than the set level. // If the level is FatalLevel, it will call Fatal regardless... func Print(l Level, v ...interface{}) { if l == FatalLevel { stdLog.Fatal(v...) return } if l <= level { defer stdLog.SetPrefix(stdLog.Prefix()) stdLog.SetPrefix(levelPrefix[l]) stdLog.Print(v...) } }
func appengineMiddleware(event *Event, config *Configuration) (err error) { var c appengine.Context for _, datum := range event.RawData { if r, ok := datum.(*http.Request); ok { c = appengine.NewContext(r) break } else if context, ok := datum.(appengine.Context); ok { c = context break } } if c == nil { return fmt.Errorf("No appengine context given") } // You can only use the builtin http library if you pay for appengine, // so we use the appengine urlfetch service instead. config.Transport = &urlfetch.Transport{ Context: c, } // Anything written to stderr/stdout is discarded, so lets log to the request. if configuredLogger, ok := config.Logger.(*log.Logger); ok { config.Logger = log.New(appengineWriter{c}, configuredLogger.Prefix(), configuredLogger.Flags()) } else { config.Logger = log.New(appengineWriter{c}, log.Prefix(), log.Flags()) } // Set the releaseStage appropriately if config.ReleaseStage == "" { if appengine.IsDevAppServer() { config.ReleaseStage = "development" } else { config.ReleaseStage = "production" } } if event.User == nil { u := user.Current(c) if u != nil { event.User = &User{ Id: u.ID, Email: u.Email, } } } return nil }
func (self *ExportContext) updateRC() (err error) { defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "update:") self.oldEnv = self.env.Copy() var backupDiff *EnvDiff if backupDiff, err = self.config.EnvDiff(); err != nil { err = fmt.Errorf("EnvDiff() failed: %q", err) return } self.oldEnv = backupDiff.Reverse().Patch(self.env) log_debug("Determining action:") log_debug("foundRC: %#v", self.foundRC) log_debug("loadedRC: %#v", self.loadedRC) switch { case self.foundRC == nil: log_debug("no RC found, unloading") err = self.unloadEnv() case self.loadedRC == nil: log_debug("no RC (implies no DIRENV_DIFF),loading") err = self.loadRC() case self.loadedRC.path != self.foundRC.path: log_debug("new RC, loading") err = self.loadRC() case self.loadedRC.times.Check() != nil: log_debug("file changed, reloading") err = self.loadRC() default: log_debug("no update needed") } return }
func runCrashyServer(rawData ...interface{}) (net.Listener, error) { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return nil, err } mux := http.NewServeMux() mux.HandleFunc("/", crashyHandler) srv := http.Server{ Addr: l.Addr().String(), Handler: Handler(mux, rawData...), ErrorLog: log.New(ioutil.Discard, log.Prefix(), 0), } go srv.Serve(l) return l, err }
// Create replicator object and return replicator interface for it func New(server cluster.Server, dirName string) Replicator { // returns replicator interface //latestTerm := uint64(1) //var logger *log.Logger /////////////////////////////// var f *os.File var err error if debug { logfile := GetPath() + "/src/github.com/nilangshah/Raft/log" + strconv.Itoa(server.Pid()) f, err = os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("error opening file: %v", err)) } else { //defer f.Close() } } ////////////////////////////// raftlog := newRaftLog(dirName) latestTerm := raftlog.lastTerm() no_of_servers = server.No_Of_Peers() quorum = ((no_of_servers - 1) / 2) + 1 r := &replicator{ s: server, term: latestTerm, leader: unknownLeader, vote: noVote, electionTick: nil, log: raftlog, state: &protectedString{value: follower}, running: &protectedBool{value: false}, isLeader: &protectedBool{value: false}, quit: make(chan chan struct{}), logger: log.New(f, log.Prefix(), log.Flags()), command_inchan: make(chan *[]byte, 1024), command_outchan: make(chan interface{}), } r.logger.Println(latestTerm) r.log.ApplyFunc = func(e *LogItem) { r.command_inchan <- &(e.Command) } r.resetElectionTimeout() return r }
// Setup ensures that all relevant job parts are configured and instatiated. func (j *Job) setup(s *Source) error { if j.ID == "" { j.ID = escapePath(path.Join(s.Owner, s.Repo)) } if j.Logger == nil { logFilePath, err := j.Config.LogFilePath(j.ID, s.Rev) if err != nil { return err } logger, err := NewFileLogger(logFilePath, log.Prefix(), log.LstdFlags) if err != nil { return err } j.Logger = logger j.Logger.Printf("[I][job] %s Created logger: %s", j.ID, j.Logger.outFile.Name()) } if j.Fetcher == nil { f := &GithubFetcher{ BaseDir: path.Join(j.Config.FetchBaseDir, s.Owner, s.Repo), LogWriter: j.Logger.outFile, Source: s, } j.Fetcher = f } if j.Config.NoNotify { j.Notifier = &DiscardNotifier{} } if j.Notifier == nil { c := NewOAuthGithubClient(j.Config.GithubToken) t := j.Config.BaseURL + fmt.Sprintf("/jobs/%s/status/%s", j.ID, escapePath(s.Rev)) n := &GithubNotifier{ Client: c, Source: s, TargetURL: t, } j.Notifier = n } return nil }
func HtmlToPdf(html []byte, outfile string, opts ...string) error { wkhtmltopdf := os.Getenv("MD2PDF_WKHTMLTOPDF") if wkhtmltopdf == "" { wkhtmltopdf = wkhtmltopdfCmd } tmp, err := ioutil.TempFile("", "") if err != nil { log.Fatal(err) } defer func() { os.Remove(tmp.Name()) }() tmp.Write(html) tmp.Close() pagefile := tmp.Name() + ".html" err = os.Rename(tmp.Name(), pagefile) if err != nil { log.Fatal(err) } defer func() { os.Remove(pagefile) }() opts = append(opts, pagefile, outfile) cmd := exec.Command(wkhtmltopdf, opts...) log.Println(strings.Join(cmd.Args, " ")) output, err := cmd.CombinedOutput() if err != nil { logger := log.New(os.Stderr, log.Prefix(), log.Flags()) logger.Println(cmd.Args) logger.Println(err) return errors.New(string(output)) } return nil }
) // `direnv edit [PATH_TO_RC]` var CmdEdit = &Cmd{ Name: "edit", Desc: `Opens PATH_TO_RC or the current .envrc into an $EDITOR and allow the file to be loaded afterwards.`, Args: []string{"[PATH_TO_RC]"}, NoWait: true, Fn: func(env Env, args []string) (err error) { var config *Config var rcPath string var times *FileTimes var foundRC *RC defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "cmd_edit: ") if config, err = LoadConfig(env); err != nil { return } foundRC = config.FindRC() if foundRC != nil { times = &foundRC.times } if len(args) > 1 { rcPath = args[1] fi, _ := os.Stat(rcPath) if fi != nil && fi.IsDir() {
func Prefix() string { return log.Prefix() }
func NewLogger() (*Logger, error) { writer := os.Stderr logger := log.New(writer, log.Prefix(), log.LstdFlags) return &Logger{logger, syslog.LOG_DEBUG}, nil }
func (l *Log) Printf(prefix, fmt string, args ...interface{}) { old := stdlog.Prefix() stdlog.SetPrefix(prefix) defer stdlog.SetPrefix(old) stdlog.Printf(fmt, args...) }
func main() { flag.Parse() cmd := flag.Args() // set up logging if !*flagSyslog { logger = log.New(os.Stderr, log.Prefix(), log.Flags()) } switch *flagServer { case true: http.HandleFunc(*flagEndpoint, root) logger.Print("bringing up endpoint") var err os.Error if *flagUseSSL { err = http.ListenAndServeTLS(*flagAddr, *flagSSLCert, *flagSSLKey, nil) } else { err = http.ListenAndServe(*flagAddr, nil) } if err != nil { log.Fatal("ListenAndServe:", err) } case false: if *flagSilent { devnull, _ := os.Open(os.DevNull) log.SetOutput(devnull) } switch { case *flagHostname == "": log.Fatal("missing hostname") case *flagServicename == "": log.Fatal("missing servicename") case len(cmd) < 1: log.Fatal("missing command(s)") } msg := new(CheckResultSet) if *flagCmdlist { for _, v := range cmd { f, err := os.Open(v) if err != nil { log.Print("error: ", err) } else { defer f.Close() runCommandList(f, msg) } } } else { runSingleCheck(msg, cmd) } buf, err := proto.Marshal(msg) if err != nil { log.Fatal("marshalling error: ", err) } PostToEndpoint(buf, *flagURL) } }
func (stdLibLog) Prefix() string { return log.Prefix() }
func main() { // Load config first since it changes the default flag values. st, err := os.Stat(config) if err == nil && st.Mode().IsRegular() { log.Printf("Load config: %v", config) LoadConfig(config, &options) } if options.Extensions == nil { // Defaults: Init here so that unspecified config options get properly set. options.Extensions = stringSetFlag{ "aac": true, "ape": true, "flac": true, "ogg": true, "m4a": true, "mp3": true, "mp4": true, "mpc": true, "wav": true, "wv": true, } } flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %v [OPTIONS] FILES|FOLDERS\n\n", os.Args[0]) fmt.Fprintln(os.Stderr, usage) fmt.Fprintln(os.Stderr, "Options:") flag.PrintDefaults() } flag.BoolVar(&options.Color, "color", options.Color, "Color output.") flag.IntVar(&options.Cores, "cores", options.Cores, "Run N processes in parallel. If 0, use all online cores.") flag.BoolVar(&options.Debug, "debug", false, "Enable debug messages.") flag.StringVar(&options.Exist, "exist", options.Exist, "Specify action to run when the destination exists. Warning: overwriting may result in undesired behaviour if destination is part of the input.") flag.Var(&options.Extensions, "ext", "Additional extensions to look for when a folder is browsed.") flag.BoolVar(&options.Getcover, "c", options.Getcover, "Fetch cover from the Internet.") flag.BoolVar(&options.Gettags, "t", options.Gettags, "Fetch tags from the Internet.") flag.StringVar(&options.Index, "i", options.Index, `Use index file to set input and output metadata. The index can be built using the non-formatted preview output.`) flag.StringVar(&options.Postscript, "post", options.Postscript, "Run Lua code after the other scripts.") flag.StringVar(&options.Prescript, "pre", options.Prescript, "Run Lua code before the other scripts.") flag.BoolVar(&options.Process, "p", options.Process, "Apply changes: set tags and format, move/copy result to destination file.") sFlag := scriptAddFlag{&options.Scripts} flag.Var(&sFlag, "s", `Specify scripts to run in lexicographical order. This option can be specified several times.`) rFlag := scriptRemoveFlag{&options.Scripts} flag.Var(&rFlag, "r", `Remove scripts where the regexp matches a part of the basename. An empty regexp removes all scripts.`) var flagVersion = flag.Bool("v", false, "Print version and exit.") flag.Parse() if *flagVersion { fmt.Println(application, version, copyright) return } if flag.Arg(0) == "" { flag.Usage() return } // Check for essential programs. _, err = exec.LookPath("ffmpeg") if err != nil { log.Fatal(err) } _, err = exec.LookPath("ffprobe") if err != nil { log.Fatal(err) } // Enable index output if stdout is redirected. st, _ = os.Stdout.Stat() if (st.Mode() & os.ModeCharDevice) == 0 { previewOptions.printIndex = true } // Disable diff preview if stderr is does not have a 'TerminalSize'. st, _ = os.Stderr.Stat() if (st.Mode() & os.ModeCharDevice) == 0 { options.Color = false previewOptions.printDiff = false } else if _, _, err := TerminalSize(int(os.Stderr.Fd())); err != nil { options.Color = false previewOptions.printDiff = false } if options.Color { log.SetPrefix(ansi.Color(log.Prefix(), "magenta+b")) warning.SetPrefix(ansi.Color(warning.Prefix(), "yellow+b")) } printExtensions() listCode() cacheScripts() cacheAction(actionExist, options.Exist) cacheIndex() // Limit number of cores to online cores. if options.Cores > runtime.NumCPU() || options.Cores <= 0 { options.Cores = runtime.NumCPU() } // Pipeline. // The log queue should be able to hold all routines at once. p := NewPipeline(1, 1+options.Cores+options.Cores) p.Add(func() Stage { return &walker{} }, 1) p.Add(func() Stage { return &analyzer{} }, options.Cores) if options.Process { p.Add(func() Stage { return &transformer{} }, options.Cores) } // Produce pipeline input. This should be run in parallel to pipeline // consumption. go func() { for _, file := range flag.Args() { visit := func(path string, info os.FileInfo, err error) error { if err != nil || !info.Mode().IsRegular() { return nil } p.input <- newFileRecord(path) return nil } // 'visit' always keeps going, so no error. _ = RealPathWalk(file, visit) } close(p.input) }() // Consume pipeline output. for fr := range p.output { p.log <- fr } p.Close() }
func TestHandler(t *testing.T) { startTestServer() l, err := runCrashyServer(Configuration{ APIKey: testAPIKey, Endpoint: testEndpoint, ProjectPackages: []string{"github.com/bugsnag/bugsnag-go"}, Logger: log.New(ioutil.Discard, log.Prefix(), log.Flags()), }, SeverityInfo) if err != nil { t.Fatal(err) } http.Get("http://" + l.Addr().String() + "/ok?foo=bar") l.Close() json, err := simplejson.NewJson(<-postedJSON) if err != nil { t.Fatal(err) } if json.Get("apiKey").MustString() != testAPIKey { t.Errorf("Wrong api key in payload") } if json.GetPath("notifier", "name").MustString() != "Bugsnag Go" { t.Errorf("Wrong notifier name in payload") } event := json.Get("events").GetIndex(0) for k, value := range map[string]string{ "payloadVersion": "2", "severity": "info", "user.id": "127.0.0.1", "metaData.Request.Url": "http://" + l.Addr().String() + "/ok?foo=bar", "metaData.Request.Method": "GET", } { key := strings.Split(k, ".") if event.GetPath(key...).MustString() != value { t.Errorf("Wrong %v: %v != %v", key, event.GetPath(key...).MustString(), value) } } if event.GetPath("metaData", "Request", "Params", "foo").GetIndex(0).MustString() != "bar" { t.Errorf("missing GET params in request metadata") } if event.GetPath("metaData", "Headers", "Accept-Encoding").GetIndex(0).MustString() != "gzip" { t.Errorf("missing GET params in request metadata: %v", event.GetPath("metaData", "Headers")) } exception := event.Get("exceptions").GetIndex(0) if exception.Get("message").MustString() != "runtime error: send on closed channel" { t.Errorf("Wrong message in payload: %v", exception.Get("message").MustString()) } if exception.Get("errorClass").MustString() != "runtime.errorCString" { t.Errorf("Wrong errorClass in payload: %v", exception.Get("errorClass").MustString()) } // TODO:CI these are probably dependent on go version. frame0 := exception.Get("stacktrace").GetIndex(0) if frame0.Get("file").MustString() != "runtime/panic.c" || frame0.Get("method").MustString() != "panicstring" || frame0.Get("inProject").MustBool() != false || frame0.Get("lineNumber").MustInt() == 0 { t.Errorf("Wrong frame0: %v", frame0) } frame3 := exception.Get("stacktrace").GetIndex(3) if frame3.Get("file").MustString() != "bugsnag_test.go" || frame3.Get("method").MustString() != "crashyHandler" || frame3.Get("inProject").MustBool() != true || frame3.Get("lineNumber").MustInt() == 0 { t.Errorf("Wrong frame3: %v", frame3) } }
func LogSomeStuff() { log.Print("Line 7: Astrid was born on Jan 30") log.Print("Line 8: pɹɐɥ sı ǝpoɔıun") log.Print("Line 9: Karl was born on Jan 10") log.Printf("log prefix: %s", log.Prefix()) }