func startCmd(cmdName string, args ...string) (*exec.Cmd, error) { var err error lvl := syslog.Priority(stdoutLevel) | syslog.Priority(facility) stdoutLog, err = syslog.New(lvl, tag) if err != nil { log.Fatalf("Error initializing stdout syslog: %v", err) } lvl = syslog.Priority(stderrLevel) | syslog.Priority(facility) stderrLog, err = syslog.New(lvl, tag) if err != nil { log.Fatalf("Error initializing stderr syslog: %v", err) } cmd := exec.Command(cmdName, args...) cmd.Stdin = os.Stdin stdoutPipe, err := cmd.StdoutPipe() if err != nil { log.Fatalf("Error initializing stdout pipe: %v", err) } stderrPipe, err := cmd.StderrPipe() if err != nil { log.Fatalf("Error initializing stderr pipe: %v", err) } wg.Add(2) go logPipe(stdoutLog, stdoutPipe) go logPipe(stderrLog, stderrPipe) return cmd, cmd.Start() }
func NewSysLogger(conf Config) (Logger, error) { debugW, err := syslog.New(syslog.LOG_MAIL|syslog.LOG_DEBUG, appname) if err != nil { return nil, err } infoW, err := syslog.New(syslog.LOG_MAIL|syslog.LOG_INFO, appname) if err != nil { return nil, err } warnW, err := syslog.New(syslog.LOG_MAIL|syslog.LOG_WARNING, appname) if err != nil { return nil, err } errorW, err := syslog.New(syslog.LOG_MAIL|syslog.LOG_ERR, appname) if err != nil { return nil, err } sev, err := SeverityFromString(conf.Severity) if err != nil { return nil, err } return &sysLogger{sev, debugW, infoW, warnW, errorW}, nil }
func main() { flag.Usage = usage flag.Parse() flag.Visit(func(f *flag.Flag) { switch f.Name { case "C": setLogLevel(*level) } }) var err error logger, err = syslog.New(0, "") ck(err) if *kern { logger.Notice("KLOGD: started with Kernel ring buffer as log source\n") kctl(1, 0) } else { fd, err = os.Open("/proc/kmsg") ck(err) logger.Notice("KLOGD: started with /proc/kmsg as log source\n") } logger.Close() logger, err = syslog.New(syslog.LOG_KERN, "Kernel") ck(err) sigCh := make(chan os.Signal) var sigs []os.Signal for i := syscall.Signal(-1); i != syscall.SIGCHLD; i++ { sigs = append(sigs, i) } signal.Notify(sigCh, sigs...) readCh := make(chan string) go reader(readCh) loop: for { select { case <-sigCh: break loop case str := <-readCh: log(str) } } logger.Notice("KLOGD: Daemon exiting......\n") if *kern { kctl(7, 0) kctl(0, 0) } else { setLogLevel(7) fd.Close() } os.Exit(1) }
func (handler *SyslogHandler) Handle(record *Record) error { if handler.writter == nil { writter, err := syslog.New(handler.Facility|handler.Severity, handler.Tag) if err != nil { return err } handler.writter = writter } msg := handler.Formatter.Format(record) switch record.Level { case EMERGENCY: return handler.writter.Emerg(msg) case ALERT: return handler.writter.Alert(msg) case CRITICAL: return handler.writter.Crit(msg) case ERROR: return handler.writter.Err(msg) case WARNING: return handler.writter.Warning(msg) case NOTICE: return handler.writter.Notice(msg) case INFO: return handler.writter.Info(msg) default: return handler.writter.Debug(msg) } }
func main() { // options var bind, backend, logTo string var buffer uint var daemon bool flag.StringVar(&bind, "bind", ":8002", "locate ip and port") flag.StringVar(&backend, "backend", "127.0.0.1:8003", "backend server ip and port") flag.StringVar(&logTo, "logTo", "stdout", "stdout or syslog") flag.UintVar(&buffer, "buffer", 4096, "buffer size") flag.BoolVar(&daemon, "daemon", false, "run as daemon process") flag.Parse() log.SetOutput(os.Stdout) if logTo == "syslog" { w, err := syslog.New(syslog.LOG_INFO, "portproxy") if err != nil { log.Fatal(err) } log.SetOutput(w) } if daemon == true { godaemon.MakeDaemon(&godaemon.DaemonAttr{}) } p := New(bind, backend, uint32(buffer)) log.Println("portproxy started.") go p.Start() waitSignal() }
func main() { var faddr, baddr, cryptoMethod, secret, logTo string var clientMode bool flag.StringVar(&logTo, "logto", "stdout", "stdout or syslog") flag.StringVar(&faddr, "listen", ":9001", "host:port qtunnel listen on") flag.StringVar(&baddr, "backend", "127.0.0.1:6400", "host:port of the backend") flag.StringVar(&cryptoMethod, "crypto", "rc4", "encryption method") flag.StringVar(&secret, "secret", "secret", "password used to encrypt the data") flag.BoolVar(&clientMode, "clientmode", false, "if running at client mode") flag.Parse() log.SetOutput(os.Stdout) if logTo == "syslog" { w, err := syslog.New(syslog.LOG_INFO, "qtunnel") if err != nil { log.Fatal(err) } log.SetOutput(w) } t := tunnel.NewTunnel(faddr, baddr, clientMode, cryptoMethod, secret, 4096) log.Println("qtunnel started.") go t.Start() waitSignal() }
func main() { kingpin.Version("2.1.0") kingpin.Parse() sl, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_LOCAL0, "[varnish-purge-proxy]") defer sl.Close() if err != nil { log.Println("Error writing to syslog") } else { log.SetFlags(0) log.SetOutput(sl) } if len(*tags) == 0 { fmt.Println("No tags specified") return } region, err = ec2metadata.New(session.New()).Region() if err != nil { log.Printf("Unable to retrieve the region from the EC2 instance %v\n", err) } // Set up access to ec2 svc := ec2.New(session.New(), &aws.Config{Region: ®ion}) go serveHTTP(*port, *listen, svc) select {} }
func SetupLogging() { syslg, err := syslog.New(syslog.LOG_ERR|syslog.LOG_DAEMON, "paperless") if err != nil { log.Fatal("Creating a syslog logger failed") } log.SetOutput(syslg) }
func main() { bind := flag.String("bind", "0.0.0.0:8080", "address to bind http server to") useSyslog := flag.Bool("syslog", false, "log to syslog") flag.Parse() if *useSyslog { logwriter, err := syslog.New(syslog.LOG_NOTICE, "todo") if err == nil { log.SetOutput(logwriter) } } log.Print("constructing service") svc, err := todo.NewTodoService(*bind) if err != nil { log.Println(err) os.Exit(1) } log.Print("migrating") if err = svc.Migrate(); err != nil { log.Println(err) os.Exit(1) } log.Print("running service") if err := svc.Run(); err != nil { log.Println(err) os.Exit(1) } }
// MAIN func main() { parseCommandLine() t, err := tail.TailFile(accessLog, tail.Config{Follow: true, ReOpen: true, MustExist: false}) if err != nil { panic(err) } hits := make(chan *loghit.LogHit) defer close(hits) errors := make(chan error) defer close(errors) for i := 0; i < *parserRoutines; i++ { go parseLines(t.Lines, hits, errors) } for i := 0; i < *posterRoutines; i++ { go postStats(*statPrefix, ezKey, hits) } logWriter, err := syslog.New(syslog.LOG_ERR, "nginx2stathat") if err != nil { panic(err) } for err := range errors { logWriter.Err(err.Error()) } }
func init() { LogWriter, SyslogError = syslog.New(syslog.LOG_INFO, "paxrat") if SyslogError != nil { // TODO: We should continue running and log to STDOUT instead using same LogWriter interface fmt.Println(SyslogError) os.Exit(0) // Exit cleanly for dpkg } InotifyFlags = (inotify.IN_DONT_FOLLOW | inotify.IN_ATTRIB | inotify.IN_CREATE | inotify.IN_DELETE_SELF | inotify.IN_MOVE_SELF | inotify.IN_MOVED_TO) InotifyDirFlags = (inotify.IN_DONT_FOLLOW | inotify.IN_CREATE | inotify.IN_DELETE_SELF | inotify.IN_MOVE_SELF | inotify.IN_MOVED_TO) Conf = new(Config) flag.StringVar(&configvar, "c", "/etc/paxrat/paxrat.conf", "Pax flags configuration file") flag.BoolVar(&testvar, "t", false, "Test the config file and then exit") flag.BoolVar(&xattrvar, "x", false, "Force use of xattr to set PaX flags") flag.BoolVar(&watchvar, "w", false, "Run paxrat in watch mode") flag.StringVar(&flagsvar, "s", "", "Set PaX flags for a single binary (must also specify binary)") flag.BoolVar(&nonrootvar, "n", false, "Set nonroot variable for a single binary (needed to set flags on a non-root owned binary)") flag.BoolVar(&nodivertvar, "d", false, "Disable checking for dpkg-divert original path (generally this should be enabled)") flag.StringVar(&binaryvar, "b", "", "Path to a binary for use with set option") flag.StringVar(&replacementvar, "r", "", "Replacement string to use in binary path JSON (ex: $REPLACEMENT in binary path)") }
func main() { var prio, tag string flag.StringVar(&prio, "p", "user.notice", "set priority") user, err := user.Current() if err == nil { tag = user.Username } flag.StringVar(&tag, "t", tag, "use tag to prefix every message") flag.Usage = usage flag.Parse() value, err := lookup(prio) ck(err) logger, err := syslog.New(value, tag) ck(err) var buf []byte if flag.NArg() < 1 { buf, err = ioutil.ReadAll(os.Stdin) ck(err) } else { buf = []byte(strings.Join(flag.Args(), " ")) } _, err = logger.Write(buf) ek(err) ek(logger.Close()) os.Exit(status) }
// MessageLogger log a message to system log func MessageLogger(syslogType syslog.Priority, message string) { if (runtime.GOOS != "nacl") && (runtime.GOOS != "plan9") && (runtime.GOOS != "windows") { // If we are using a syslog supported OS syslogLogger, _ := syslog.New(syslogType, "Metis") // Create a new syslogLogger that logs as error as LOG_USER syslogLogger.Write([]byte(message)) // Write the message syslogLogger.Close() // Close the logger } }
func init() { f, err := os.OpenFile("/var/log/hello.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println("error opening file: %v", err) } defer f.Close() log.SetOutput(f) log.Println("This is a test log entry") //log2Syslog logwriter, e := syslog.New(syslog.LOG_NOTICE, "hello") if e == nil { log.SetOutput(logwriter) log.Print("Initialization Complete!") } mWriter := io.MultiWriter(f, logwriter) data := []byte("Hello World MultiWriter!") n, err := mWriter.Write(data) if err == nil { fmt.Printf("Multi write %d bytes to two files simultaneously.\n", n) } }
func newSyslogLogger() Logger { w, err := syslog.New(syslog.LOG_INFO, "tsuru") if err != nil { log.Fatal(err) } return &syslogLogger{w} }
func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof.StartCPUProfile(f) go func() { time.Sleep(60 * time.Second) pprof.StopCPUProfile() panic("done") }() } config, err := LoadConfig(*config_file) if err != nil { return } event_chan := make(chan *FileEvent, 16) publisher_chan := make(chan []*FileEvent, 1) registrar_chan := make(chan []*FileEvent, 1) if len(config.Files) == 0 { log.Fatalf("No paths given. What files do you want me to watch?\n") } // The basic model of execution: // - prospector: finds files in paths/globs to harvest, starts harvesters // - harvester: reads a file, sends events to the spooler // - spooler: buffers events until ready to flush to the publisher // - publisher: writes to the network, notifies registrar // - registrar: records positions of files read // Finally, prospector uses the registrar information, on restart, to // determine where in each file to resume a harvester. log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) if *use_syslog { writer, err := syslog.New(syslog.LOG_INFO|syslog.LOG_DAEMON, "lumberjack") if err != nil { log.Fatalf("Failed to open syslog: %s\n", err) } log.SetOutput(writer) } // Prospect the globs/paths given on the command line and launch harvesters for _, fileconfig := range config.Files { go Prospect(fileconfig, event_chan) } // Harvesters dump events into the spooler. go Spool(event_chan, publisher_chan, *spool_size, *idle_timeout) go Publishv1(publisher_chan, registrar_chan, &config.Network) // registrar records last acknowledged positions in all files. Registrar(registrar_chan) } /* main */
func NewSyslogLogger(tag string, debug bool) Logger { w, err := syslog.New(syslog.LOG_INFO, tag) if err != nil { log.Fatal(err) } return &syslogLogger{w: w, debug: debug} }
func (l *Logger) log(text string, priority syslog.Priority) { w, err := syslog.New(priority, l.prefix) defer w.Close() if err != nil { panic(err) } switch priority { case syslog.LOG_DEBUG: w.Debug(text) case syslog.LOG_INFO: w.Info(text) case syslog.LOG_NOTICE: w.Notice(text) case syslog.LOG_WARNING: w.Warning(text) case syslog.LOG_ERR: w.Err(text) case syslog.LOG_CRIT: w.Crit(text) case syslog.LOG_ALERT: w.Alert(text) case syslog.LOG_EMERG: w.Emerg(text) } }
func main() { var err error TTY = isatty(os.Stdin.Fd()) getopts() getUser() parseConfigs() if ssh_cmd := os.Getenv("SSH_ORIGINAL_COMMAND"); len(ssh_cmd) > 0 { GIVEN_COMMANDS = ssh_cmd } setEnvironment() LOGGER, err = syslog.New(syslog.LOG_INFO|syslog.LOG_AUTH, PROGNAME) if err != nil { fail(fmt.Sprintf("Unable to open syslog: %v\n", err)) } if len(GIVEN_COMMANDS) > 0 { processInput(GIVEN_COMMANDS) } else { readExecLoop() } os.Exit(LAST_RVAL) /* NOTREACHED */ }
func main() { logwriter, e := syslog.New(syslog.LOG_NOTICE, programName) if e == nil { log.SetOutput(logwriter) } cmd.Log(fmt.Sprintf("%s version: %s", programName, Version), "info") args := os.Args[1:] for _, arg := range args { if arg == "-v" || arg == "--version" { fmt.Printf("Version : %s\nRevision : %s\nDate : %s\nGo : %s\n", Version, GitCommit, CompileDate, GoVersion) os.Exit(0) } } // Setup nice shutdown with CTRL-C. c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go handleCtrlC(c) // Listen for expvar if we have GOSHE_DEBUG set. if os.Getenv("GOSHE_DEBUG") != "" { go setupExpvarHTTP() } cmd.RootCmd.Execute() }
func Start(file string) (syslog.Writer, domains.Config) { golog, err := syslog.New(syslog.LOG_ERR, "golog") defer golog.Close() if err != nil { log.Fatal("error writing syslog!!") } f, err := os.Open(file) if err != nil { panic(err) } defer f.Close() buf, err := ioutil.ReadAll(f) if err != nil { panic(err) } // var config tomlConfig if err := toml.Unmarshal(buf, &config); err != nil { panic(err) } return *golog, config }
func main() { db, err = sql.Open("mysql", "root:haosoo8888@tcp(127.0.0.1:3306)/call?charset=utf8") if err != nil { log.Fatal(err) } db.SetMaxOpenConns(2000) db.SetMaxIdleConns(1000) defer db.Close() err = db.Ping() if err != nil { fmt.Println("数据库连接错误!") } pool = newPool(redisServer) // Init a syslog writter for our test l, errLog := syslog.New(syslog.LOG_INFO, "TestFSock") if errLog != nil { l.Crit(fmt.Sprintf("Cannot connect to syslog:", errLog)) return } // No filters evFilters := map[string]string{} // We are interested in heartbeats, define handler for them evHandlers := map[string][]func(string){"CHANNEL_CREATE": []func(string){printChannelCreate}, "CHANNEL_ANSWER": []func(string){printChannelAnswer}, "CHANNEL_HANGUP_COMPLETE": []func(string){printChannelHungup}} // evHandlers := map[string][]func(string){"CHANNEL_CREATE": []func(string){printChannelCreate}} fs, err := fsock.NewFSock("127.0.0.1:8021", "ClueCon", 10, evHandlers, evFilters, l) if err != nil { l.Crit(fmt.Sprintf("FreeSWITCH error:", err)) return } fs.ReadEvents() }
func newSysLogger(name string, errs chan<- error) (Logger, error) { w, err := syslog.New(syslog.LOG_INFO, name) if err != nil { return nil, err } return sysLogger{w, errs}, nil }
func main() { // the lazy man solution: set the rsyslog instance as the log.std object so it // can be shared across all files. Another option is to follow the code under // http://golang.org/src/pkg/log/log.go to create a synched singleton rsyslog // writer slog, err := syslog.New(syslog.LOG_INFO, "goxy") log.SetOutput(slog) log.SetFlags(log.Lshortfile) log.Println("hello from goxy") flag.Parse() log.Println("listening on port ", gPortStr) ln, err := net.Listen("tcp", gPortStr) if err != nil { // handle error } for { conn, err := ln.Accept() if err != nil { // handle error continue } log.Println("mainloop received: ", conn.LocalAddr(), conn.RemoteAddr()) go proxy.Handle(conn) } }
func main() { var err error log, err = syslog.New(syslog.LOG_INFO, "gandalf-listener") if err != nil { fmt.Fprintln(os.Stderr, err.Error()) panic(err.Error()) } err = config.ReadConfigFile("/etc/gandalf.conf") if err != nil { log.Err(err.Error()) fmt.Fprintln(os.Stderr, err.Error()) return } _, _, err = parseGitCommand() if err != nil { log.Err(err.Error()) fmt.Fprintln(os.Stderr, err.Error()) return } a := action() if a == "git-receive-pack" { executeAction(hasWritePermission, "You don't have access to write in this repository.", os.Stdout) return } if a == "git-upload-pack" { executeAction(hasReadPermission, "You don't have access to read this repository.", os.Stdout) return } }
func main() { kingpin.Version("1.2.1") kingpin.Parse() sl, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_LOCAL0, "[varnish-purge-proxy]") defer sl.Close() if err != nil { log.Println("Error writing to syslog") } else { log.SetFlags(0) log.SetOutput(sl) } if len(*tags) == 0 { fmt.Println("No tags specified") return } // Set up access to ec2 auth, err := aws.GetAuth("", "", "", time.Now().Add(time.Duration(24*365*time.Hour))) if err != nil { log.Println(err) return } ec2region := ec2.New(auth, region) go serveHTTP(*port, ec2region) select {} }
func init() { var err error logger, err = syslog.New(syslog.LOG_NOTICE, "gitblog") if err != nil { log.Fatal(err) } }
func NewSyslogWriter(p syslog.Priority, tag string) LoggaWriter { sw := &SyslogWriter{priority: p} sw.writer, _ = syslog.New(p, tag) sw.buffer = new(bytes.Buffer) sw.formatter = golog.New(sw.buffer, "", 0) return LoggaWriter(sw) }
func TestSingleton(t *testing.T) { t.Parallel() log1 := GetAuditLogger() test.AssertNotNil(t, log1, "Logger shouldn't be nil") log2 := GetAuditLogger() test.AssertEquals(t, log1, log2) writer, err := syslog.New(syslog.LOG_EMERG|syslog.LOG_KERN, "tag") test.AssertNotError(t, err, "Could not construct syslog object") stats, _ := statsd.NewNoopClient(nil) log3, err := NewAuditLogger(writer, stats) test.AssertNotError(t, err, "Could not construct audit logger") // Should not work err = SetAuditLogger(log3) test.AssertError(t, err, "Can't re-set") // Verify no change log4 := GetAuditLogger() // Verify that log4 != log3 test.AssertNotEquals(t, log4, log3) // Verify that log4 == log2 == log1 test.AssertEquals(t, log4, log2) test.AssertEquals(t, log4, log1) }
func main() { var serverNet, serverAddr string flag.StringVar(&serverNet, "is-net", "tcp", "Network for APRS-IS server") flag.StringVar(&serverAddr, "is-addr", ":10152", "Bind address for APRS-IS server") useSyslog := flag.Bool("syslog", false, "Log to syslog") flag.Parse() if *useSyslog { sl, err := syslog.New(syslog.LOG_INFO, "aprs-gate") if err != nil { log.Fatalf("Error initializing syslog") } log.SetOutput(sl) log.SetFlags(0) } broadcaster := broadcast.NewBroadcaster(100) // go reporter(broadcaster) go notify(broadcaster) if *server != "" { go readNet(broadcaster) } if *portString != "" { go readSerial(broadcaster) } go startIS(serverNet, serverAddr, broadcaster) log.Fatal(http.ListenAndServe(*httpAddr, nil)) }