当前位置: 首页>>代码示例>>Golang>>正文


Golang debug.Stack函数代码示例

本文整理汇总了Golang中runtime/debug.Stack函数的典型用法代码示例。如果您正苦于以下问题:Golang Stack函数的具体用法?Golang Stack怎么用?Golang Stack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Stack函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: RunSpec

func RunSpec(dir string, pkg *tp.Package, eng tritium.Engine, logger *golog.Logger) (result *Result) {
	result = NewResult()

	defer func() {
		//log.Println("done")  // Println executes normally even in there is a panic
		if x := recover(); x != nil {
			err, ok := x.(error)
			if ok {
				logger.Errorf(dir + " === " + err.Error() + "\n\n" + string(debug.Stack()))
			} else {
				logger.Errorf(dir + " === " + x.(string) + "\n\n" + string(debug.Stack()))
			}
		}
		print(result.CharStatus())
	}()

	spec, err := LoadSpec(dir, pkg)
	if err != nil {
		result.Error(dir, err.Error())
	} else {
		d, _ := time.ParseDuration("1m")
		result.Merge(spec.Compare(eng.Run(spec.Script, nil, spec.Input, spec.Vars, time.Now().Add(d), "test", "test", "test", false)))
	}
	return
}
开发者ID:nmakiya,项目名称:tritium,代码行数:25,代码来源:runner.go

示例2: DevelopmentRecovery

func DevelopmentRecovery(p *prago.Request, recoveryData interface{}) {
	if p.App().DevelopmentMode {
		temp, err := template.New("development_error").Parse(developmentErrorTmpl)
		if err != nil {
			panic(err)
		}

		byteData := fmt.Sprintf("%s", recoveryData)

		buf := new(bytes.Buffer)
		err = temp.ExecuteTemplate(buf, "development_error", map[string]interface{}{
			"name":    byteData,
			"subname": "500 Internal Server Error",
			"stack":   string(debug.Stack()),
		})
		if err != nil {
			panic(err)
		}

		p.Response().Header().Add("Content-type", "text/html")
		p.Response().WriteHeader(500)
		p.Response().Write(buf.Bytes())

	} else {
		p.Response().WriteHeader(500)
		p.Response().Write([]byte("We are sorry, some error occured. (500)"))
	}

	p.Log().Errorln(fmt.Sprintf("500 - error\n%s\nstack:\n", recoveryData))
	p.Log().Errorln(string(debug.Stack()))
}
开发者ID:hypertornado,项目名称:prago,代码行数:31,代码来源:development.go

示例3: handle

func handle(conn net.Conn) {
	defer func() {
		conn.Close()
		if err := recover(); err != nil {
			printf("panic: %v\n\n%s", err, debug.Stack())
		}
	}()

	agent := handshake(conn)
	if agent == nil {
		return
	}
	defer agent.Close()

	go func() {
		defer func() {
			agent.Close()
			conn.Close()
			if err := recover(); err != nil {
				printf("panic: %v\n\n%s", err, debug.Stack())
			}
		}()
		copy(conn, agent)
	}()
	copy(agent, conn)
}
开发者ID:uin57,项目名称:gateway,代码行数:26,代码来源:main.go

示例4: ServeHTTP

func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	defer func() {
		if err := recover(); err != nil {
			if rw.Header().Get("Content-Type") == "" {
				rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
			}

			rw.WriteHeader(http.StatusInternalServerError)

			stack := make([]byte, rec.StackSize)
			stack = stack[:runtime.Stack(stack, rec.StackAll)]

			f := "PANIC: %s\n%s"
			rec.Logger.Printf(f, err, stack)

			if rec.PrintStack {
				fmt.Fprintf(rw, f, err, stack)
			}

			if rec.ErrorHandlerFunc != nil {
				func() {
					defer func() {
						if err := recover(); err != nil {
							rec.Logger.Printf("provided ErrorHandlerFunc panic'd: %s, trace:\n%s", err, debug.Stack())
							rec.Logger.Printf("%s\n", debug.Stack())
						}
					}()
					rec.ErrorHandlerFunc(err)
				}()
			}
		}
	}()

	next(rw, r)
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:35,代码来源:recovery.go

示例5: PrintPanicStack

func PrintPanicStack() {
	if err := recover(); err != nil {
		now := time.Now()
		if now.Unix() != panic_time {
			panic_time = now.Unix()
			panic_count = 0
		}
		panic_count++

		_, app_name := path.Split(strings.Replace(os.Args[0], "\\", "/", -1))
		app_name = strings.Split(app_name, ".")[0]

		fileName := fmt.Sprintf("panic_%s_%s_%d.log", app_name, now.Format("2006-01-02-15_04_05"), panic_count)
		fmt.Println(fileName)

		fmt.Println(err)
		fmt.Println(string(debug.Stack()))

		file, _ := os.OpenFile("./panic/"+fileName, os.O_CREATE, 0666)
		if file != nil {
			file.WriteString(fmt.Sprintln(err))
			file.WriteString("\n==============\n")
			file.WriteString(string(debug.Stack()))
			file.Close()
		}
	}
}
开发者ID:playnb,项目名称:mustang,代码行数:27,代码来源:tools.go

示例6: dockerSetup

// dockerSetup does all of the basic setup you need to get a running docker
// process up and running for testing. Use like:
//
//	task := taskTemplate()
//	// do custom task configuration
//	client, handle, cleanup := dockerSetup(t, task)
//	defer cleanup()
//	// do test stuff
//
// If there is a problem during setup this function will abort or skip the test
// and indicate the reason.
func dockerSetup(t *testing.T, task *structs.Task) (*docker.Client, DriverHandle, func()) {
	if !testutil.DockerIsConnected(t) {
		t.SkipNow()
	}

	client, err := docker.NewClientFromEnv()
	if err != nil {
		t.Fatalf("Failed to initialize client: %s\nStack\n%s", err, debug.Stack())
	}

	driverCtx, execCtx := testDriverContexts(task)
	driver := NewDockerDriver(driverCtx)

	handle, err := driver.Start(execCtx, task)
	if err != nil {
		execCtx.AllocDir.Destroy()
		t.Fatalf("Failed to start driver: %s\nStack\n%s", err, debug.Stack())
	}
	if handle == nil {
		execCtx.AllocDir.Destroy()
		t.Fatalf("handle is nil\nStack\n%s", debug.Stack())
	}

	cleanup := func() {
		handle.Kill()
		execCtx.AllocDir.Destroy()
	}

	return client, handle, cleanup
}
开发者ID:hooklift,项目名称:nomad,代码行数:41,代码来源:docker_test.go

示例7: ServeHTTP

// ServeHTTP routing function
func (t *Trouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(w, "error: %s\nat:\n%s", e, debug.Stack())
			t.errorLog.Printf("error: %s\nat:\n%s", e, debug.Stack())
		}
	}()

	urlParts := strings.SplitN(r.URL.Path[1:], "/", 50)

	// Find action
	action := t.routes[r.Method+strings.ToLower(urlParts[0])]
	// Action nil
	if action == nil {
		t.notFound(w, r)
		return
	}
	// Action get file
	if action.actionType == actionTypeFile {
		action.action(w, r)
		return
	}

	// Parse url to parameters
	r.ParseForm()
	urlParts = urlParts[1:]
	count := util.Min(len(urlParts), len(action.prm))
	for id := 0; id < count; id++ {
		if len(urlParts[id]) > 0 {
			r.Form.Set(action.prm[id], urlParts[id])
		}
	}
	action.action(w, r)
}
开发者ID:catgatp,项目名称:gol,代码行数:35,代码来源:router.go

示例8: Compile

func (task *task) Compile() (e error) {
	if task.compiled {
		return nil
	}
	m := message(pubsub.MessageTasksPrecompile, "", task.name)
	m.Publish("started")
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			e, ok = r.(error)
			if !ok {
				e = fmt.Errorf("failed to precompile package: %v %q", task.name, r)
			}
			m.Error = e
			m.Stack = string(debug.Stack())
			m.Publish("panic")
			log.Printf("ERROR: %s", r)
			log.Print(string(debug.Stack()))
		}
	}()

	e = task.validate()
	if e != nil {
		return e
	}
	m.Publish("finished")
	task.compiled = true
	return nil
}
开发者ID:rajthilakmca,项目名称:urknall,代码行数:29,代码来源:task.go

示例9: readAndAssertStr

func readAndAssertStr(t *T, client *clients.Client, expected string) {
	rr := redis.NewRespReader(client.Conn)
	m := rr.Read()
	require.Nil(t, m.Err, "stack:\n%s", debug.Stack())
	s, err := m.Str()
	require.Nil(t, err, "stack:\n%s", debug.Stack())
	assert.Equal(t, expected, s, "m: %v stack:\n%s", m, debug.Stack())
}
开发者ID:mc0,项目名称:okq,代码行数:8,代码来源:commands_test.go

示例10: err

// Just printing the stack trace to http response if a panic bubbles up all the way to top.
func err() {
	if r := recover(); r != nil {
		fmt.Println("at main:", r)
		fmt.Println(string(debug.Stack()))
		Put(unfortunate_error)
		Put(fmt.Sprint("\n", r, "\n\n"+string(debug.Stack())))
	}
}
开发者ID:Laller,项目名称:hypecms,代码行数:9,代码来源:main.go

示例11: readAndAssertInt

func readAndAssertInt(t *T, client *clients.Client, expected int64) {
	rr := redis.NewRespReader(client.Conn)
	m := rr.Read()
	require.Nil(t, m.Err, "stack:\n%s", debug.Stack())
	i, err := m.Int64()
	require.Nil(t, err, "stack:\n%s", debug.Stack())
	assert.Equal(t, expected, i, "m: %v stack:\n%s", m, debug.Stack())
}
开发者ID:mc0,项目名称:okq,代码行数:8,代码来源:commands_test.go

示例12: DefaultGetErrorText

func DefaultGetErrorText(m interface{}) string {
	switch v := m.(type) {
	case string:
		return fmt.Sprintf("PANIC: %s\n%s", v, debug.Stack())
	case error:
		return fmt.Sprintf("PANIC: %s\n%s", v.Error(), debug.Stack())
	default:
		return fmt.Sprintf("PANIC: %v\n%s", v, debug.Stack())
	}
}
开发者ID:patrickToca,项目名称:go-middleware,代码行数:10,代码来源:handler.go

示例13: getLevelContext

func (hd *HappyDevFormatter) getLevelContext(level int, entry map[string]interface{}) (message string, context string, color string) {

	switch level {
	case LevelTrace:
		color = theme.Trace
		context = hd.getContext(color)
		context += "\n"
	case LevelDebug:
		color = theme.Debug
	case LevelInfo:
		color = theme.Info
	case LevelWarn:
		color = theme.Warn
		context = hd.getContext(color)
		context += "\n"
	case LevelError, LevelFatal:
		color = theme.Error
		if disableCallstack || contextLines == -1 {
			context = trimDebugStack(string(debug.Stack()))
			break
		}
		frames := parseLogxiStack(entry, 4, true)
		if frames == nil {
			frames = parseDebugStack(string(debug.Stack()), 4, true)
		}

		if len(frames) == 0 {
			break
		}
		errbuf := pool.Get()
		defer pool.Put(errbuf)
		lines := 0
		for _, frame := range frames {
			err := frame.readSource(contextLines)
			if err != nil {
				// by setting to empty, the original stack is used
				errbuf.Reset()
				break
			}
			ctx := frame.String(theme.Error, theme.Source)
			if ctx == "" {
				continue
			}
			errbuf.WriteString(ctx)
			errbuf.WriteRune('\n')
			lines++
		}
		context = errbuf.String()
	default:
		panic("should never get here")
	}
	return message, context, color
}
开发者ID:blacklabeldata,项目名称:serfer,代码行数:53,代码来源:happyDevFormatter.go

示例14: handleInvocationPanic

// This function handles a panic in an action invocation.
// It cleans up the stack trace, logs it, and displays an error page.
func handleInvocationPanic(c *Controller, err interface{}) {
	error := NewErrorFromPanic(err)
	if error == nil {
		ERROR.Print(err, "\n", string(debug.Stack()))
		c.Response.Out.WriteHeader(500)
		c.Response.Out.Write(debug.Stack())
		return
	}

	ERROR.Print(err, "\n", error.Stack)
	c.Result = c.RenderError(error)
}
开发者ID:jevonearth,项目名称:revel,代码行数:14,代码来源:panic.go

示例15: handleInvocationPanic

// This function handles a panic in an action invocation.
// It cleans up the stack trace, logs it, and displays an error page.
func handleInvocationPanic(c *Controller, err interface{}) {
	error := NewErrorFromPanic(err)
	if error == nil && DevMode {
		// Only show the sensitive information in the debug stack trace in development mode, not production
		ERROR.Print(err, "\n", string(debug.Stack()))
		c.Response.Out.WriteHeader(500)
		c.Response.Out.Write(debug.Stack())
		return
	}

	ERROR.Print(err, "\n", error.Stack)
	c.Result = c.RenderError(error)
}
开发者ID:acroidea,项目名称:baron-core,代码行数:15,代码来源:panic.go


注:本文中的runtime/debug.Stack函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。