Esempio n. 1
0
func main() {

	var dsn string
	if len(os.Args) >= 2 {
		dsn = strings.Join(os.Args[1:], " ")
	} else {
		dsn = os.Getenv("SENTRY_DSN")
	}

	if dsn == "" {
		fmt.Printf("Error: No configuration detected!\n")
		fmt.Printf("You must either pass a DSN to the command, or set the SENTRY_DSN environment variable\n")
		return
	}

	fmt.Printf("Using DSN configuration:\n %v\n", dsn)
	client, err := raven.NewClient(dsn)

	if err != nil {
		fmt.Printf("could not connect: %v", dsn)
		return
	}

	fmt.Printf("Sending a test message...\n")
	id, err := client.CaptureMessage("This is a test message generated using ``goraven test``")

	if err != nil {
		fmt.Printf("failed: %v\n", err)
		return
	}

	fmt.Printf("Message captured, id: %v", id)
}
Esempio n. 2
0
func LogPrintf(format string, v ...interface{}) {
	log.Printf(format, v)
	if ravenDSN == "" {
		return
	}
	client, err := raven.NewClient(ravenDSN)
	if err != nil {
		log.Printf("LogPrintf: could not connect: %v", ravenDSN)
		return
	}
	_, err = client.CaptureMessage(fmt.Sprintf(format, v))
	if err != nil {
		log.Printf("LogPrintf: failed logging with raven")
		return
	}
}
/*
Middleware that catches panics, and:

	- logs them
	- optionally reports them to sentry - pass in "" if you don't want this
	- sends a 500 response

You can also use ThrowError() to raise an error that this middleware will catch, for example
if you want an error to be reported to sentry
*/
func BuildErrorCatcher(sentryDSN string) func(c *web.C, h http.Handler) http.Handler {
	var sentryClient *raven.Client
	if sentryDSN != "" {
		var err error
		sentryClient, err = raven.NewClient(sentryDSN)
		if err != nil {
			log.Printf("Couldn't connect to sentry %v\n", err)
		}
	}

	return func(c *web.C, h http.Handler) http.Handler {
		handler := func(w http.ResponseWriter, r *http.Request) {

			defer func() {
				err := recover()
				if err == nil {
					return
				}
				if sentryClient != nil {
					// Send the error to sentry
					const size = 1 << 12
					buf := make([]byte, size)
					n := runtime.Stack(buf, false)
					sentryClient.CaptureMessage(fmt.Sprintf("%v\nStacktrace:\n%s", err, buf[:n]))
				}

				switch err := err.(type) {
				case HttpError:
					log.Printf("Return response for error %s", err.Message)
					err.WriteResponse(w)
					return
				default:
					log.Printf("Panic: %v\n", err)
					debug.PrintStack()
					http.Error(w, http.StatusText(500), 500)
					return
				}
			}()

			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(handler)
	}
}
Esempio n. 4
0
func init() {
	var err error
	mongo_server := os.Getenv("OPENSHIFT_MONGODB_DB_URL")
	if mongo_server == "" {
		db_session, err = mgo.Dial("localhost")
	} else {
		db_session, err = mgo.Dial(mongo_server + MONGO_DB_NAME)
	}
	if err != nil {
		log.Print("db connection: ", err)
	}
	// register bson's ObjectId with the gob for cookie encoding
	gob.Register(bson.ObjectId(""))
	gob.RegisterName("app/models.Flash", &Flash{"", ""})
	gob.RegisterName("app/models.Filter", &Filter{})

	database = db_session.DB("").Name
	Router = pat.New()
	//create an index for the email field on the users collection
	if err := db_session.DB(database).C("users").EnsureIndex(mgo.Index{
		Key:    []string{"email"},
		Unique: true,
	}); err != nil {
		log.Print("context: ", err)
	}
	if err := db_session.DB(database).C("users").EnsureIndexKey("location"); err != nil {
		log.Print("context: ", err)
	}
	if err := db_session.DB(database).C("users").EnsureIndexKey("country"); err != nil {
		log.Print("context: ", err)
	}
	store = sessions.NewCookieStore([]byte("508a664e65427d3f91000001"))
	if sentry, err = raven.NewClient(SENTRY_DSN); err != nil {
		log.Print("could not connect to sentry: ", err)
	}
	loadTranslations()
}
Esempio n. 5
0
func main() {
	var dsn string

	// How does this return an error ?
	defaultHostname, _ := os.Hostname()

	project := flag.String("project", "", "The project name to use for the event")
	timestamp := flag.String("timestamp", "", "The (iso8601) timestamp to use for the event")
	level := flag.String("level", "error", "The logging level to send")
	logger := flag.String("logger", "root", "The logger name to use for the event")
	hostname := flag.String("hostname", defaultHostname, "The host to report for")
	//exception := flag.String("exception", "", "An exception (gdb format) to report for")

	tags := make(DataMap)
	flag.Var(tags, "tag", "List of tags of the form name=value")

	modules := make(DataMap)
	flag.Var(modules, "module", "Add a module of the form name=value")

	extras := make(DataMap)
	flag.Var(extras, "extra", "Add an extra of the form name=value")

	flag.Parse()

	dsn = flag.Arg(0)

	if dsn == "" {
		dsn = os.Getenv("SENTRY_DSN")
	}

	if dsn == "" {
		fmt.Printf("Error: No configuration detected!\n")
		fmt.Printf("You must either pass a DSN to the command, or set the SENTRY_DSN environment variable\n")
		os.Exit(1)
	}

	client, err := raven.NewClient(dsn)

	if err != nil {
		fmt.Printf("could not connect: %v", dsn)
		os.Exit(2)
	}

	bytes, err := ioutil.ReadAll(os.Stdin)

	if err != nil {
		panic("Unable to read from stdin ?")
	}

	plat := platform.GetPlatform()

	event := raven.Event{
		Message:    string(bytes),
		ServerName: *hostname,
		Project:    *project,
		Level:      *level,
		Timestamp:  *timestamp,
		Logger:     *logger,
		Tags:       tags,
		Modules:    modules,
		Extra:      extras,
		Platform:   fmt.Sprintf("%s - %s", plat.OSName, plat.Release),
	}

	sentryErr := client.Capture(&event)

	if sentryErr != nil {
		fmt.Printf("failed: %v\n", err)
		os.Exit(3)
	}
}
Esempio n. 6
0
// initServer initializes the global Server variable.
// Should be called only once: after the first call, it does nothing.
func (s *server) Init(confPath string) (err error) {
	// do not let be Initialized multiple times
	if s.Initialized {
		return
	}

	s.Logger = log.New(os.Stdout, "[agora-http-go] ", 0)
	s.Mux = medeina.NewMedeina()

	// parse config
	confStr, err := util.Contents(confPath)
	if err != nil {
		s.Logger.Printf("Error reading config file %s %v", confPath, err)
		return
	}

	var cfg map[string]*json.RawMessage
	err = json.Unmarshal([]byte(confStr), &cfg)
	if err != nil {
		s.Logger.Printf("Error reading config file %s %v", confPath, err)
		return
	}

	json.Unmarshal(*cfg["Debug"], &s.Debug)
	json.Unmarshal(*cfg["DbMaxIddleConnections"], &s.DbMaxIddleConnections)
	json.Unmarshal(*cfg["DbConnectString"], &s.DbConnectString)
	json.Unmarshal(*cfg["SharedSecret"], &s.SharedSecret)
	json.Unmarshal(*cfg["Admins"], &s.Admins)
	json.Unmarshal(*cfg["ActiveModules"], &s.ActiveModules)
	json.Unmarshal(*cfg["RavenDSN"], &s.RavenDSN)

	// configure database
	s.DbConnectString = os.ExpandEnv(s.DbConnectString)
	s.Logger.Print("connecting to postgres: " + s.DbConnectString)
	s.Db, err = sqlx.Connect("postgres", s.DbConnectString)
	if err != nil {
		return
	}
	s.Db.SetMaxIdleConns(s.DbMaxIddleConnections)

	// construct the http server
	s.Http = negroni.Classic()
	s.Http.Use(negroni.NewRecovery())
	if s.Debug {
		s.Logger.Print("In debug mode")
		s.Http.Use(negroni.NewLogger())
	}
	s.Http.UseHandler(s.Mux)

	// if there's a DSN configured, try to connect with raven
	if len(s.RavenDSN) > 0 {
		if s.Raven, err = raven.NewClient(s.RavenDSN); err != nil {
			s.Logger.Printf("Error configuring raven with DSN %s: %v", s.RavenDSN, err)
		}
	}
	s.Http.Use(middleware.NewRecoveryJson(s.Logger, s.Raven))

	// create the errorwrap middleware
	s.ErrorWrap = middleware.NewErrorWrap(s, s.Logger)

	// init modules, only once the server instance has been configured, and
	// only those modules that user wants to activate
	for _, module := range s.AvailableModules {
		var (
			mod_name = module.Name()
		)
		// find the module, and init it if found
		for _, active_module := range s.ActiveModules {
			if mod_name != active_module {
				continue
			}
			s.Logger.Print("Loading module: " + mod_name)
			if err = module.Init(cfg); err != nil {
				s.Logger.Fatal(err)
			}
			break
		}
	}

	s.Initialized = true
	return
}