本文整理汇总了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
}
示例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()))
}
示例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)
}
示例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)
}
示例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()
}
}
}
示例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
}
示例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)
}
示例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
}
示例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())
}
示例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())))
}
}
示例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())
}
示例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())
}
}
示例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
}
示例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)
}
示例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)
}