예제 #1
0
파일: log.go 프로젝트: rockstar/lxd
// SetLogger defines the *log.Logger where log messages are sent to.
func SetLogger(syslog string, logfile string, verbose bool, debug bool) error {
	Log = log.New()

	var handlers []log.Handler

	var syshandler log.Handler

	// System specific handler
	syshandler = GetSystemHandler(syslog, debug)
	if syshandler != nil {
		handlers = append(handlers, syshandler)
	}

	// FileHandler
	if logfile != "" {
		if !PathExists(filepath.Dir(logfile)) {
			return fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
		}

		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlInfo,
					log.Must.FileHandler(logfile, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))
		}
	}

	// StderrHandler
	if verbose || debug {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlInfo,
					log.StderrHandler,
				),
			)
		} else {
			handlers = append(handlers, log.StderrHandler)
		}
	} else {
		handlers = append(
			handlers,
			log.LvlFilterHandler(
				log.LvlWarn,
				log.StderrHandler,
			),
		)
	}

	Log.SetHandler(log.MultiHandler(handlers...))

	return nil
}
예제 #2
0
파일: log.go 프로젝트: RuneTM/lxd
// SetLogger defines the *log.Logger where log messages are sent to.
func SetLogger(syslog string, logfile string, verbose bool, debug bool) error {
	Log = log.New()

	var handlers []log.Handler

	// SyslogHandler
	if syslog != "" {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.Must.SyslogHandler(syslog, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.SyslogHandler(syslog, log.LogfmtFormat()))
		}
	}

	// FileHandler
	if logfile != "" {
		if !PathExists(filepath.Dir(logfile)) {
			return fmt.Errorf("Log file path doesn't exist: %s\n", filepath.Dir(logfile))
		}

		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.Must.FileHandler(logfile, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))
		}
	}

	// StderrHandler
	if verbose || debug {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.StderrHandler,
				),
			)
		} else {
			handlers = append(handlers, log.StderrHandler)
		}
	}

	Log.SetHandler(log.MultiHandler(handlers...))

	return nil
}
예제 #3
0
파일: log.go 프로젝트: joker042/lxd
// SetLogger defines the *log.Logger where log messages are sent to.
func SetLogger(syslog string, logfile string, verbose bool, debug bool) {
	Log = log.New()

	var handlers []log.Handler

	// SyslogHandler
	if syslog != "" {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.Must.SyslogHandler(syslog, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.SyslogHandler(syslog, log.LogfmtFormat()))
		}
	}

	// FileHandler
	if logfile != "" {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.Must.FileHandler(logfile, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))
		}
	}

	// StderrHandler
	if verbose || debug {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlError,
					log.StderrHandler,
				),
			)
		} else {
			handlers = append(handlers, log.StderrHandler)
		}
	}

	Log.SetHandler(log.MultiHandler(handlers...))
}
예제 #4
0
파일: log_posix.go 프로젝트: ccsblueboy/lxd
// getSystemHandler on Linux writes messages to syslog.
func getSystemHandler(syslog string, debug bool) log.Handler {
	// SyslogHandler
	if syslog != "" {
		if !debug {
			return log.LvlFilterHandler(
				log.LvlInfo,
				log.Must.SyslogHandler(syslog, log.LogfmtFormat()),
			)
		} else {
			return log.Must.SyslogHandler(syslog, log.LogfmtFormat())
		}
	}

	return nil
}
예제 #5
0
파일: main.go 프로젝트: seka17/bracelet
func main() {
	start := false
	logDir := flag.String("log", "./logs", "path to log directory")
	confPath := flag.String("config", "./config.json", "path to cofig file")
	// docker := flag.Bool("docker", false, "for docker")
	flag.Parse()

	// Create log directory
	if err := os.Mkdir(*logDir, 0777); err != nil && os.IsNotExist(err) {
		log.Fatal(err)
	}
	// Write log in file:
	// Change file every 24 hours
	go func() {
		Log = llog.New()
		t := time.Now()
		for {
			// Day_Month_Year
			name := fmt.Sprintf("%v.%v.%v", t.Month(), t.Day(), t.Year())
			h, f, err := MyFileHandler(path.Join(*logDir, name), llog.LogfmtFormat())
			if err != nil {
				log.Println(err)
				return
			}
			Log.SetHandler(llog.SyncHandler(h))
			if !start {
				start = true
			}
			t = <-time.After(24 * time.Second)
			Log.SetHandler(llog.DiscardHandler())
			f.Close()
		}
	}()
	// Wait for log setup
	for {
		if start {
			break
		}
		time.Sleep(time.Second * 5)
	}

	file, err := ioutil.ReadFile(*confPath)
	if err != nil {
		fmt.Println("No config.json provided, using default values!")
		os.Exit(1)
	}

	var conf proxy.Config
	if err := json.Unmarshal(file, &conf); err != nil {
		os.Exit(1)
	}
	// creates new server instance using config.json
	s := proxy.NewServer(Log, conf)

	if err := s.Listen(); err != nil {
		Log.Error("Listen", "error", err)
		os.Exit(1)
	}

}
예제 #6
0
파일: axiom.go 프로젝트: postfix/axiom
func (w *Logged) HandlerFor(target, level, format string) (log.Handler, error) {
	lvl, err := log.LvlFromString(level)
	if err != nil {
		return nil, fmt.Errorf("Invalid log level: %v", err)
	}

	var logformat log.Format
	switch format {
	case "json":
		logformat = log.JsonFormat()
	case "logfmt":
		logformat = log.LogfmtFormat()
	case "terminal", "term":
		switch {
		case target == "stdout" && term.IsTty(os.Stdout.Fd()):
			logformat = log.TerminalFormat()
		case target == "stderr" && term.IsTty(os.Stderr.Fd()):
			logformat = log.TerminalFormat()
		default:
			logformat = log.LogfmtFormat()
		}
	default:
		return nil, fmt.Errorf("Invalid log format: %v", format)
	}

	var handler log.Handler
	switch target {
	case "stdout":
		handler = log.StreamHandler(colorable.NewColorableStdout(), logformat)
	case "stderr":
		handler = log.StreamHandler(colorable.NewColorableStderr(), logformat)
	case "false":
		handler = log.DiscardHandler()
	default:
		handler, err = log.FileHandler(target, logformat)
		if err != nil {
			return nil, fmt.Errorf("Failed to open log file '%s': %v", target, err)
		}
	}

	return log.LvlFilterHandler(lvl, handler), nil
}
예제 #7
0
// InitLog ...
func (logM *LogManager) InitLog() {

	var svrlog = log.New(logM.LogContext, logM.LogContext)
	svrlog.SetHandler(log.MultiHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()),
		log.LvlFilterHandler(log.LvlError, log.Must.FileHandler(logM.LogDir+logM.ErrorFile, log.JsonFormat())),
		log.LvlFilterHandler(log.LvlInfo, log.Must.FileHandler(logM.LogDir+logM.InfoFile, log.JsonFormat())),
		log.LvlFilterHandler(log.LvlCrit, log.Must.FileHandler(logM.LogDir+logM.CritFile, log.JsonFormat())),
		log.LvlFilterHandler(log.LvlDebug, log.Must.FileHandler(logM.LogDir+logM.DebugFile, log.JsonFormat()))))

	logM.Logger = svrlog

}
예제 #8
0
func New() *Engine {
	// package instance of the helios type
	engine := &Engine{
		HTTPEngine: gin.Default(),
		Socket:     initSocket(),
		Logger:     log.New(),
	}

	fileHandler, _ := log.FileHandler("./log.debug", log.LogfmtFormat())
	engine.SetHandler(log.MultiHandler(log.LvlFilterHandler(log.LvlWarn, fileHandler), log.StreamHandler(os.Stdout, log.TerminalFormat())))

	return engine
}
예제 #9
0
func BenchmarkLog15TextPositive(b *testing.B) {
	stream := &blackholeStream{}
	logger := log.New()
	logger.SetHandler(log.StreamHandler(stream, log.LogfmtFormat()))
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			logger.Info("The quick brown fox jumps over the lazy dog")
		}
	})

	if stream.WriteCount() != uint64(b.N) {
		b.Fatalf("Log write count")
	}
}
예제 #10
0
func setSettings(level int, filename string) {
	logFilename = filename
	debug = level

	filehandler := log.Must.FileHandler(filename, log.LogfmtFormat())
	handler := log.MultiHandler(
		filehandler,
		log.StreamHandler(os.Stderr, log.TerminalFormat()))
	if debug > 1 {
		handler = log.CallerStackHandler("%+v", handler)
	} else {
		handler = log.CallerFileHandler(handler)
	}
	if debug < 1 {
		handler = log.LvlFilterHandler(log.LvlInfo, handler)
	}
	log.Root().SetHandler(handler)
	log.Info("Logging started", "level", debug, "log_file", logFilename)
}
예제 #11
0
파일: logger.go 프로젝트: cloud66/cxlogger
func (l *Logger) Initialize(logOut string, lvl interface{}) error {
	var (
		level log.Lvl
		err   error
	)

	if l.Context == "" {
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		randInt := r.Int()
		t := time.Now()
		l.Context = fmt.Sprintf("%s#%d", t.Format(time.RFC3339), randInt)
	}

	if str, ok := lvl.(string); ok {
		level, err = log.LvlFromString(str)
		if err != nil {
			return err
		}
	} else {
		level = lvl.(log.Lvl)
	}
	l.Logger = log.New(log.Ctx{"context": l.Context})
	l.Level = level

	if logOut == "STDOUT" {
		normalHandler := log.LvlFilterHandler(level, log.StdoutHandler)
		errorHandler := log.LvlFilterHandler(level, log.CallerStackHandler("%+v", log.StdoutHandler))
		handler := errorMultiHandler(normalHandler, errorHandler)
		l.SetHandler(handler)
	} else if logOut == "NONE" {
		l.SetHandler(log.DiscardHandler())
	} else {
		fileHandler := log.Must.FileHandler(logOut, log.LogfmtFormat())
		normalHandler := log.LvlFilterHandler(level, fileHandler)
		errorHandler := log.LvlFilterHandler(level, log.CallerStackHandler("%+v", fileHandler))
		handler := errorMultiHandler(normalHandler, errorHandler)
		l.SetHandler(handler)
	}

	return nil
}
예제 #12
0
func TestMain(m *testing.M) {
	Log := llog.New()
	h, _ := llog.FileHandler("./test.txt", llog.LogfmtFormat())
	Log.SetHandler(h)
	server = s.NewServer(Log, ":81234")
	n, err := nats.Connect("nats://localhost:4222")
	if err != nil {
		llog.Error("Can't connect to NATS", "error", err)
		return
	}
	nc, _ := nats.NewEncodedConn(n, nats.JSON_ENCODER)
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		nc.Close()
		llog.Error("Can't listen on provided port", "error", err)
		return
	}
	server.BC = l
	server.NC = nc
	server.Loc, _ = time.LoadLocation(s.BraceletLocation)
	log.Println("Connections established")
	os.Exit(m.Run())
}
예제 #13
0
func New() *Engine {
	// package instance of the helios type
	engine := &Engine{
		HTTPEngine: gin.Default(),
		Logger:     log.New(),
	}

	fileHandler, _ := log.FileHandler("./error.log", log.LogfmtFormat())
	engine.SetHandler(log.MultiHandler(log.LvlFilterHandler(log.LvlWarn, fileHandler), log.StreamHandler(os.Stdout, log.TerminalFormat())))

	socket, err := initSocket()
	if err != nil {
		engine.Error("Failed to initialize socket server")
	}

	// Handle error cases
	socket.On("error", func(so socketio.Socket, err error) {
		engine.Error("Error on socket.io server", "error", err.Error())
	})

	engine.Socket = socket

	return engine
}
예제 #14
0
파일: log.go 프로젝트: rintcius/go-suffuse
func level(max lg.Lvl) lg.Logger {
	l := lg.New()
	handler := lg.StreamHandler(os.Stdout, lg.LogfmtFormat())
	l.SetHandler(lg.LvlFilterHandler(max, handler))
	return l
}
예제 #15
0
파일: main.go 프로젝트: ts2/ts2-sim-server
func main() {
	// Command line arguments
	port := flag.String("port", server.DEFAULT_PORT, "The port on which the server will listen")
	addr := flag.String("addr", server.DEFAULT_ADDR, "The address on which the server will listen. Set to 0.0.0.0 to listen on all addresses.")
	logFile := flag.String("logfile", "", "The filename in which to save the logs. If not specified, the logs are sent to stderr.")
	logLevel := flag.String("loglevel", "info", "The minimum level of log to be written. Possible values are 'crit', 'error', 'warn', 'info' and 'debug'.")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, `Usage of ts2-sim-server:
  ts2-sim-server [options...] file

ARGUMENTS:
  file
		The JSON simulation file to load

OPTIONS:
`)
		flag.PrintDefaults()
	}

	flag.Parse()

	// Handle ctrl+c to kill on terminal
	killChan := make(chan os.Signal, 1)
	signal.Notify(killChan, os.Interrupt)

	// Setup logging system
	logger = log.New()
	var outputHandler log.Handler
	if *logFile != "" {
		outputHandler = log.Must.FileHandler(*logFile, log.LogfmtFormat())
	} else {
		outputHandler = log.StderrHandler
	}
	logLvl, err_level := log.LvlFromString(*logLevel)
	if err_level != nil {
		fmt.Fprintf(os.Stderr, "Error: Unknown loglevel\n\n")
		flag.Usage()
		os.Exit(1)
	}
	logger.SetHandler(log.LvlFilterHandler(
		logLvl,
		outputHandler,
	))
	simulation.InitializeLogger(logger)
	server.InitializeLogger(logger)

	// Load the simulation
	if len(flag.Args()) == 0 {
		fmt.Fprintf(os.Stderr, "Error: Please specify a simulation file\n\n")
		flag.Usage()
		os.Exit(1)
	}
	simFile := flag.Arg(0)
	logger.Info("Loading simulation", "file", simFile)

	data, err := ioutil.ReadFile(simFile)
	if err != nil {
		logger.Crit("Unable to read file", "file", simFile, "error", err)
		os.Exit(1)
	}

	var sim simulation.Simulation
	errload := json.Unmarshal(data, &sim)

	if errload != nil {
		logger.Error("Load Error", "file", simFile, "error", errload)
		return
	}
	logger.Info("Simulation loaded", "sim", sim.Options.Title)

	go server.Run(&sim, *addr, *port)

	// Route all messages
	for {
		select {

		case <-killChan:
			// TODO gracefully shutdown things maybe
			logger.Info("Server killed, exiting...")
			os.Exit(0)
		}
	}
}