Example #1
0
// Start Logger service
func (self *Logger) Start() {
	var err error
	self.Logger = log.New()
	if self.Release {
		self.Level, err = log.LvlFromString("error")
		if err != nil {
			fmt.Println(err)
		}
	} else {
		self.Level, err = log.LvlFromString("debug")
		if err != nil {
			fmt.Println(err)
		}
	}
	self.Logger.SetHandler(log.LvlFilterHandler(self.Level, log.StdoutHandler))
	// self.SetHandler(log.LvlFilterHandler(lvl, log.DiscardHandler()))
	self.Info("starting Logger service...")
}
Example #2
0
func InitLogger(slvl string) {
	if slvl == "" {
		slvl = "debug"
	}
	lvl, err := log.LvlFromString(slvl)
	if err != nil {
		panic(err)
	}
	Log.SetHandler(log.LvlFilterHandler(lvl, log.StreamHandler(os.Stdout, log.TerminalFormat())))
	return
}
Example #3
0
func BenchmarkLog15Discard(b *testing.B) {
	logger := log.New()
	lvl, err := log.LvlFromString("error")
	if err != nil {
		b.Fatal(err)
	}
	logger.SetHandler(log.LvlFilterHandler(lvl, log.DiscardHandler()))

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		logger.Debug("benchmark", "i", i, "b.N", b.N)
	}
}
Example #4
0
// SetLevelStr sets the log level of the default logger, using the default log
// handler. Possible values include "off", "debug", "info", "warn", "error" and
// "crit"
func SetLevelStr(lvlstr string) {
	switch lvlstr {
	case "off":
		Log.SetHandler(log.DiscardHandler()) // discard all output
	default:
		lvl, err := log.LvlFromString(lvlstr)
		if err == nil {
			setLevel(lvl)
			break
		}
		fmt.Printf("(!) error setting error level with string %s, will turn off logs", lvlstr)
		Log.SetHandler(log.DiscardHandler()) // discard all output
	}
}
Example #5
0
File: main.go Project: jackc/tpr
func setFilterHandler(level string, logger log.Logger, handler log.Handler) error {
	if level == "none" {
		logger.SetHandler(log.DiscardHandler())
		return nil
	}

	lvl, err := log.LvlFromString(level)
	if err != nil {
		return fmt.Errorf("Bad log level: %v", err)
	}
	logger.SetHandler(log.LvlFilterHandler(lvl, handler))

	return nil
}
Example #6
0
func BenchmarkSelectWithLoggingErrorWithLog15(b *testing.B) {
	connConfig := *defaultConnConfig

	logger := log.New()
	lvl, err := log.LvlFromString("error")
	if err != nil {
		b.Fatal(err)
	}
	logger.SetHandler(log.LvlFilterHandler(lvl, log.DiscardHandler()))
	connConfig.Logger = logger
	connConfig.LogLevel = pgx.LogLevelError
	conn := mustConnect(b, connConfig)
	defer closeConn(b, conn)

	benchmarkSelectWithLog(b, conn)
}
Example #7
0
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
}
Example #8
0
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
}
Example #9
0
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)
		}
	}
}
Example #10
0
File: main.go Project: pgpst/tunnel
func main() {
	// Load the configuration
	m := multiconfig.NewWithPath(os.Getenv("config"))
	cfg := &dns.Config{}
	m.MustLoad(cfg)

	// Parse the log level
	lvl, err := log.LvlFromString(cfg.LogLevel)
	if err != nil {
		panic(err)
	}

	// Create a new logger
	l := log.New()
	l.SetHandler(
		log.LvlFilterHandler(lvl, log.StdoutHandler),
	)

	// Start the initialization
	il := l.New("module", "init")
	il.Info("Starting up the application")

	// Parse the Redis connection string
	url := redisurl.Parse(cfg.Redis)

	// Create an options list
	opts := []redis.DialOption{}
	if url.Database != 0 {
		opts = append(opts, redis.DialDatabase(url.Database))
	}
	if url.Password != "" {
		opts = append(opts, redis.DialPassword(url.Password))
	}

	// Verify the DNS setup
	results, err := net.LookupNS(cfg.Domain)
	if err != nil {
		il.Warn("Unable to look up the NS of domain", "domain", cfg.Domain, "error", err.Error())
	}
	if len(results) > 0 {
		found := false
		for _, record := range results {
			if record.Host == cfg.Hostname {
				found = true
			}
		}
		if !found {
			existing := []string{}
			for _, record := range results {
				existing = append(existing, record.Host)
			}

			il.Warn("Invalid NS records for the domain", "domain", cfg.Domain, "records", existing)
		}
	} else {
		il.Warn("No NS records found for domain", "domain", cfg.Domain, "error", err.Error())
	}

	// Dial the server
	rc, err := redis.Dial("tcp", url.Host+":"+strconv.Itoa(url.Port), opts...)
	if err != nil {
		il.Crit("Unable to connect to the Redis server", "error", err.Error())
		return
	}

	// Initialize the DNS server
	ds := &dns.DNS{
		Config: cfg,
		Redis:  rc,
	}
	if err := ds.ListenAndServe(); err != nil {
		il.Crit("Error while listening to the specified port", "error", err.Error())
	}
}