Golang(14)Error Handle Debugging Logging
1. Error Handle
func Open(name string) (file *File, err error)
It will return the err if we open file fail.
f, err := os.Open(“filename.ext”)
if err != nil {
log.Fatal(err)
}
Error Type
type error interface {
Error() string
}
There is one method in the interface error.
implementation of error interface
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
fund New(text string) error {
return &errorString{text}
}
We can use New to create one error instance.
For example>
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New(“math: square root of negative number”)
}
…snip...
}
Customer Error Type
type SyntaxError struct {
msg string
Offset int64
}
func (e *SyntaxError) Error() string { return e.msg }
Error Handle
We can deal the error in our router like this>
func viewRecord(w http.ResponseWriter, r *http.Request) {
…snip…
if err := datastore.Get(c, key, record); err != nil {
http.Error(w, err.Error(), 500)
return
}
if err := viewTemplate.Execute(w, record); err != nil {
http.Error(w, err.Error(), 500)
}
}
It works, but we need to put these error handle codes there again and again.
type appHandler func(http.ResponseWriter, *http.Request) error
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := fn(w,r); err != nil {
http.Error(w, err.Error(), 500)
}
}
func init() {
http.Handle(“/view”, appHandler(viewRecord))
}
Then our viewRecord function can be like this.
func viewRecord(w http.ResponseWriter, r *http.Request) error {
…snip..
if err := datastore.Get(c, key, record); err != nil {
return err
}
return viewTemplate.Execute(w, record)
}
We can define the Error Type ourselves.
type appError struct {
Error error
Message string
Code int
}
type appHandler func(http.ResponseWriter, *http.Request) *appError
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil {
http.Error(w, e.Message, e.Code)
}
}
If we use our customized Error Type, we can change the viewRecord like this.
func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
…snip…
if err := datastore.Get(c, key, record); err != nil {
return &appError{err, “record not found”, 404 }
}
if err := viewTemplate.Execute(w, record); err != nil {
return &appError{err, “Can not display record”, 500}
}
return nil
}
2. Use GDB Debugging
…snip...
3. Writing the Test
…snip…
4. Try seelog
Install the module
>go get -u github.com/cihub/seelog
The Simplest Example works
package main
import log "github.com/cihub/seelog"
func main() {
defer log.Flush()
log.Info("Hello from Seelog!")
}
Create the module logs
I create the directory and file logs/LogCustom.go with codes
package logs
import (
"fmt"
seelog "github.com/cihub/seelog"
)
var Logger seelog.LoggerInterface
func loadAppConfig() {
logger, err := seelog.LoggerFromConfigAsFile("/Users/carl/work/easy/easygo/src/com/sillycat/easygoapp/seelog.xml")
if err != nil {
fmt.Println(err)
return
}
UseLogger(logger)
}
func init() {
DisableLog()
loadAppConfig()
}
// DisableLog disables all library log output
func DisableLog() {
Logger = seelog.Disabled
}
// UseLogger uses a specified seelog.LoggerInterface to output library log.
// Use this func if you are using Seelog logging system in your app.
func UseLogger(newLogger seelog.LoggerInterface) {
Logger = newLogger
}
My logsee.xml will be as follow, we can change more configure based the doc from seelog
<seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug">
<exceptions>
<exception filepattern="test*" minlevel="error"/>
</exceptions>
<outputs formatid="all">
<file path="all.log"/>
<filter levels="info">
<console formatid="fmtinfo"/>
</filter>
<filter levels="error,critical" formatid="fmterror">
<console/>
<file path="errors.log"/>
</filter>
</outputs>
<formats>
<format id="fmtinfo" format="[%Level] [%Time] %Msg%n"/>
<format id="fmterror" format="[%LEVEL] [%Time] [%FuncShort @ %File.%Line] %Msg%n"/>
<format id="all" format="[%Level] [%Time] [@ %File.%Line] %Msg%n"/>
<format id="criticalemail" format="Critical error on our server!\n %Time %Date %RelFile %Func %Msg \nSent by Seelog"/>
</formats>
</seelog>
Then we build the customized module like this
>go build src/com/sillycat/easygoapp/logs/LogCustom.go
Then I can use it like this>
package main
import (
"com/sillycat/easygoapp/logs"
)
func main() {
addr := "locahost"
logs.Logger.Info("Start server at:", addr)
err := "Fail to start the server."
logs.Logger.Critical("Server err:", err)
}
This is the right way how we can manage our modules and codes in our own projects.
References:
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/11.1.md
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/11.2.md
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/11.3.md
https://github.com/cihub/seelog
http://godoc.org/github.com/cihub/seelog
- 浏览: 2567476 次
- 性别:
- 来自: 成都
-
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 492NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 351Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 449Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 401Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 496NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 438Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 346Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 262GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 463GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 336GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 322Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 330Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 320Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 307NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 272Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 586NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 279Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 388Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 387Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
Golang error具有的一切 - 它是一个替代品,因为它实现了error接口 Golang errors包提供的一切 您可以将 JSON 错误写入您的网络处理程序 文档 示例输出 json,嵌套错误,详细信息:跟踪 { " error_code " : 10 , ...
Golang通过内置的`error`接口提供了灵活且强大的错误处理机制。本篇文章将深入探讨`error`接口及其在实际编程中的应用。 `error`接口非常简单,它只有一个方法`Error() string`,用于返回一个字符串,该字符串通常...
在Golang中,如果你想要实现音频播放功能,特别是在处理MP3文件时,可以利用外部库,比如BASS库。BASS是一个广泛使用的音频处理库,它提供了强大的音频播放、流处理和格式转换功能。在Golang中使用BASS库通常需要...
weixin-golang-sdk 微信golang工具包
在Golang中,大文件上传是一项常见的任务,特别是在构建Web应用程序时。`golang大文件上传`这个主题涉及到了如何高效、安全地处理用户上传的大型文件。在本篇文章中,我们将深入探讨Golang实现大文件上传的关键知识...
Golang Windows 1.19.1版本安装包
在本文中,我们将深入探讨如何配置Golang环境以及如何使用Golang对接Amazon S3对象存储。首先,让我们从安装Golang环境开始。 1. **安装Go环境** - **Windows**:在Windows操作系统上,你可以从Go的官方网站下载...
在Golang生态系统中,`golang.org/x`是一个非常重要的包集合,它包含了大量由Go官方维护和贡献的扩展库。这些包覆盖了各种功能,从网络编程到文本处理,为Go开发者提供了丰富的工具和解决方案。`golang.org/x`包系列...
Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 Windows安装包。Golang 1.18.10 ...
golang_http_client
标题中的"Pycharm Golang插件 jar"指的是在PyCharm这款流行的Python集成开发环境中安装Golang编程语言的扩展插件。PyCharm是由JetBrains公司开发的一款强大的IDE,它支持多种编程语言,包括Python、Go等。由于Golang...
golang.org/x/sys/windows
golang 实现海康相机抓拍,目前只支持球机。需要在代码中设置用户名和密码。 如何调试?用vscode打开,安装golang插件,即可直接调试运行。 编译与运行:运行go build命令,将HKnet.exe拷贝到build\Windows下,运行...
Golang,作为一种现代且高效的编程语言,因其强大的系统级编程能力和并发特性而受到广泛欢迎。在本文中,我们将深入探讨如何利用Golang实现这个功能,并了解相关的核心知识点。 首先,我们需要了解的是Golang的图形...
本文将深入探讨如何在Golang中解析PKCS#1和PKCS#8格式的私钥,以及与数字证书相关的概念。 首先,让我们了解一些基本概念: 1. **数字证书(Digital Certificate)**:也称为X.509证书,是一种标准格式,用于在...
golang提取office文件内容,可以支持正常office文件内容格式,可以很好的提取标点以及内在格式内容
golang函数查询手册.chm
Golang中文API,由热心网友翻译上传
Go语言,又称Golang,是由Google开发的一种静态类型、编译型、并发型且具有垃圾回收功能的编程语言。它设计的目标是提高开发者的生产效率,同时保持系统级编程的性能。Go语言的设计受到了C、 Pascal、 Miranda和...
docker golang 基础包1.20-alpine