Example #1
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 #2
0
func (d *Daemon) Init() error {

	/* Setup the TLS authentication */
	certf, keyf, err := shared.ReadMyCert("client.crt", "client.key")
	if err != nil {
		return err
	}
	d.certf = certf
	d.keyf = keyf
	d.tlsConfig, err = shared.GetTLSConfig(d.certf, d.keyf)
	if err != nil {
		return err
	}
	srvlog := log.New(log.Ctx{"module": "client"})
	d.log = srvlog

	handler := log.StdoutHandler

	if quiet {
		d.log.SetHandler(log.DiscardHandler())
	} else if verbose {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlInfo, handler))
	} else if debug {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlDebug, handler))
	} else {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlError, handler))
	}

	d.Run()
	return nil
}
Example #3
0
// NewBot creates a new instance of Bot
func NewBot(host, nick string, options ...func(*Bot)) (*Bot, error) {
	// Defaults are set here
	bot := Bot{
		Incoming:      make(chan *Message, 16),
		outgoing:      make(chan string, 16),
		started:       time.Now(),
		unixastr:      fmt.Sprintf("@%s-%s/bot", host, nick),
		Host:          host,
		Nick:          nick,
		ThrottleDelay: 200 * time.Millisecond,
		PingTimeout:   300 * time.Second,
		HijackSession: false,
		SSL:           false,
		SASL:          false,
		Channels:      []string{"#test"},
		Password:      "",
	}
	for _, option := range options {
		option(&bot)
	}
	// Discard logs by default
	bot.Logger = log.New("id", logext.RandId(8), "host", bot.Host, "nick", log.Lazy{bot.getNick})

	bot.Logger.SetHandler(log.DiscardHandler())
	bot.AddTrigger(pingPong)
	bot.AddTrigger(joinChannels)
	return &bot, nil
}
Example #4
0
// NewConnPool creates a new ConnPool. config.ConnConfig is passed through to
// Connect directly.
func NewConnPool(config ConnPoolConfig) (p *ConnPool, err error) {
	p = new(ConnPool)
	p.config = config.ConnConfig
	p.maxConnections = config.MaxConnections
	if p.maxConnections == 0 {
		p.maxConnections = 5
	}
	if p.maxConnections < 2 {
		return nil, errors.New("MaxConnections must be at least 2")
	}

	p.afterConnect = config.AfterConnect
	if config.Logger != nil {
		p.logger = config.Logger
	} else {
		p.logger = log.New()
		p.logger.SetHandler(log.DiscardHandler())
	}

	p.allConnections = make([]*Conn, 0, p.maxConnections)
	p.availableConnections = make([]*Conn, 0, p.maxConnections)
	p.cond = sync.NewCond(new(sync.Mutex))

	// Initially establish one connection
	var c *Conn
	c, err = p.createConnection()
	if err != nil {
		return
	}
	p.allConnections = append(p.allConnections, c)
	p.availableConnections = append(p.availableConnections, c)

	return
}
Example #5
0
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)
	}

}
Example #6
0
func sockHandler(d *Daemon, w *websocket.Conn) {
	r := w.Request()
	raddr := r.RemoteAddr
	if !d.isTrustedClient(r) {
		d.log.Warn("untrusted client connected", log.Ctx{"raddr": raddr})
		return
	}

	d.log.Debug("handing over client connection", log.Ctx{"raddr": raddr})

	clog := log.New(log.Ctx{"module": "socks", "raddr": raddr})
	handler := log.StdoutHandler

	if quiet {
		clog.SetHandler(log.DiscardHandler())
	} else if verbose {
		clog.SetHandler(log.LvlFilterHandler(log.LvlInfo, handler))
	} else if debug {
		clog.SetHandler(log.LvlFilterHandler(log.LvlDebug, handler))
	} else {
		clog.SetHandler(log.LvlFilterHandler(log.LvlError, handler))
	}

	client := &clientConnection{
		websocket: w,
		log:       clog,
		raddr:     raddr,
	}
	go client.run()
}
Example #7
0
func main() {
	flag.Parse()
	if helpflag {
		flag.Usage()
		return
	}

	logger = log.New()

	handler := log.StdoutHandler
	if quietflag {
		logger.SetHandler(log.DiscardHandler())
	} else if verboseflag {
		logger.SetHandler(log.LvlFilterHandler(log.LvlInfo, handler))
	} else if debugflag {
		logger.SetHandler(log.LvlFilterHandler(log.LvlDebug, handler))
	} else {
		logger.SetHandler(log.LvlFilterHandler(log.LvlError, handler))
	}

	ldifstore := &ldif.LdifBackend{
		Path: "./ldif",
		Log:  logger.New(log.Ctx{"type": "backend", "backend": "ldif"}),
	}

	if err := ldifstore.Start(); err != nil {
		logger.Error("error loading backend", log.Ctx{"error": err})
		os.Exit(1)
	}

	//Create a new LDAP Server
	server := ldap.NewServer(logger)

	fallback := &debug.DebugBackend{
		Log: logger.New(log.Ctx{"type": "backend", "backend": "debug"}),
	}

	//Create routes bindings
	routes := newRouter(fallback, logger)

	// backend specific routes
	routes.Bind(ldifstore).BaseDn("dc=enterprise,dc=org").Label("Bind LDIF")
	routes.Search(ldifstore).BaseDn("dc=enterprise,dc=org").Label("Search LDIF")
	routes.Add(ldifstore).BaseDn("dc=enterprise,dc=org").Label("Add LDIF")

	//Attach routes to server
	server.Handle(routes)

	// listen on 3389 and serve
	go server.ListenAndServe(":6389")

	// When CTRL+C, SIGINT and SIGTERM signal occurs
	// Then stop server gracefully
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	<-ch
	close(ch)

	server.Stop()
}
Example #8
0
func NewUpdater(equinoxAppId, publicKeyPEM string) *Updater {
	logger := log.New()
	logger.SetHandler(log.DiscardHandler())
	return &Updater{
		Logger:         logger,
		EquinoxAppId:   equinoxAppId,
		PublicKeyPEM:   publicKeyPEM,
		DefaultChannel: "stable",
	}
}
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
0
func (d *Daemon) Init() error {

	/* Setup the TLS authentication */
	certf, keyf, err := shared.ReadMyCert("server.crt", "server.key")
	if err != nil {
		return err
	}
	d.certf = certf
	d.keyf = keyf
	d.tlsConfig, err = shared.GetTLSConfig(d.certf, d.keyf)
	if err != nil {
		return err
	}

	srvlog := log.New(log.Ctx{"module": "server"})
	d.log = srvlog

	handler := log.StdoutHandler

	if quiet {
		d.log.SetHandler(log.DiscardHandler())
	} else if verbose {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlInfo, handler))
	} else if debug {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlDebug, handler))
	} else {
		d.log.SetHandler(log.LvlFilterHandler(log.LvlError, handler))
	}

	err = initializeDbObject(d, "server.db")
	if err != nil {
		return err
	}
	readSavedClientCAList(d)

	return d.Run()
}
Example #15
0
func init() {
	Log.SetHandler(log.DiscardHandler())
}
func init() {
	// Discard logging
	Log = log15.New()
	Log.SetHandler(log15.DiscardHandler())
}
Example #17
0
File: conn.go Project: rjammala/pgx
// Connect establishes a connection with a PostgreSQL server using config.
// config.Host must be specified. config.User will default to the OS user name.
// Other config fields are optional.
func Connect(config ConnConfig) (c *Conn, err error) {
	c = new(Conn)

	c.config = config
	if c.config.Logger != nil {
		c.logger = c.config.Logger
	} else {
		c.logger = log.New()
		c.logger.SetHandler(log.DiscardHandler())
	}

	if c.config.User == "" {
		user, err := user.Current()
		if err != nil {
			return nil, err
		}
		c.config.User = user.Username
		c.logger.Debug("Using default connection config", "User", c.config.User)
	}

	if c.config.Port == 0 {
		c.config.Port = 5432
		c.logger.Debug("Using default connection config", "Port", c.config.Port)
	}

	// See if host is a valid path, if yes connect with a socket
	_, err = os.Stat(c.config.Host)
	if err == nil {
		// For backward compatibility accept socket file paths -- but directories are now preferred
		socket := c.config.Host
		if !strings.Contains(socket, "/.s.PGSQL.") {
			socket = filepath.Join(socket, ".s.PGSQL.") + strconv.FormatInt(int64(c.config.Port), 10)
		}

		c.logger.Info(fmt.Sprintf("Dialing PostgreSQL server at socket: %s", socket))
		c.conn, err = net.Dial("unix", socket)
		if err != nil {
			c.logger.Error(fmt.Sprintf("Connection failed: %v", err))
			return nil, err
		}
	} else {
		c.logger.Info(fmt.Sprintf("Dialing PostgreSQL server at host: %s:%d", c.config.Host, c.config.Port))
		c.conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", c.config.Host, c.config.Port))
		if err != nil {
			c.logger.Error(fmt.Sprintf("Connection failed: %v", err))
			return nil, err
		}
	}
	defer func() {
		if c != nil && err != nil {
			c.conn.Close()
			c.alive = false
			c.logger.Error(err.Error())
		}
	}()

	c.RuntimeParams = make(map[string]string)
	c.preparedStatements = make(map[string]*PreparedStatement)
	c.alive = true

	if config.TLSConfig != nil {
		c.logger.Debug("Starting TLS handshake")
		if err = c.startTLS(); err != nil {
			c.logger.Error(fmt.Sprintf("TLS failed: %v", err))
			return
		}
	}

	c.reader = bufio.NewReader(c.conn)
	c.mr.reader = c.reader

	msg := newStartupMessage()
	msg.options["user"] = c.config.User
	if c.config.Database != "" {
		msg.options["database"] = c.config.Database
	}
	if err = c.txStartupMessage(msg); err != nil {
		return
	}

	for {
		var t byte
		var r *msgReader
		t, r, err = c.rxMsg()
		if err != nil {
			return nil, err
		}

		switch t {
		case backendKeyData:
			c.rxBackendKeyData(r)
		case authenticationX:
			if err = c.rxAuthenticationX(r); err != nil {
				return nil, err
			}
		case readyForQuery:
			c.rxReadyForQuery(r)
			c.logger = c.logger.New("pid", c.Pid)
			c.logger.Info("Connection established")
			return c, nil
		default:
			if err = c.processContextFreeMsg(t, r); err != nil {
				return nil, err
			}
		}
	}
}
Example #18
0
func init() {
	Log.SetHandler(log.DiscardHandler()) // Off by default
}