当前位置:网站首页>Use of go log package log
Use of go log package log
2022-06-27 23:24:00 【Cloud idle】
1、log brief introduction
golang Built in log package , Implement a simple log service . By calling log Function of the package , Simple log printing function can be realized .
2、log Use
log There is... In the bag 3 A series of log printing functions , , respectively, print series 、panic series 、fatal series .
Function series effect
print Print log only
panic Print log , Throw out panic abnormal
fatal Print log , Force end procedure (os.Exit(1)),defer Function does not execute
2.1 A simple example
func main() {
defer fmt.Println(“panic Processing before exiting ”)
log.Println(“println journal ”)
log.Panic(“panic journal ”)
log.Fatal(“ Program exit log ”)
}
Result example ( The actual result is not like this , because panic,fatal Will affect the execution of the program ):
2020/06/02 11:04:17 println journal
2020/06/02 11:04:17 panic journal
2020/06/02 11:04:17 panic Processing before exiting
2020/06/02 11:04:17 Program exit log
3、log To configure
3.1 standard log To configure
By default log Only the time will be printed , But in practice, we may also need to get the file name , Line number and other information ,log The package provides us with customized interfaces .
log The package provides two standards log Configuration related methods :
func Flags() int // Return to standard log Output configuration
func SetFlags(flag int) // Set standards log Output configuration
flag Parameters
const (
// Control details of output log information , Unable to control the order and format of the output .
// Output logs are separated by a colon after each entry : for example 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
Ldate = 1 << iota // date :2009/01/23
Ltime // Time :01:23:23
Lmicroseconds // Microsecond level time :01:23:23.123123( For enhancement Ltime position )
Llongfile // File full pathname + Line number : /a/b/c/d.go:23
Lshortfile // file name + Line number :d.go:23( Will overwrite Llongfile)
LUTC // Use UTC Time
LstdFlags = Ldate | Ltime // standard logger The initial value of the
)
Example of standard log configuration
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func main() {
log.Println(“println journal ”)
}
Output results :
image.png
3.2 Log prefix configuration
log Package provides two related functions for log prefix configuration :
func Prefix() string // Returns the prefix configuration of the log
func SetPrefix(prefix string) // Set the log prefix
Log prefix configuration instance
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.SetPrefix(“success”)
}
func main() {
log.Println(“println journal ”)
}
Output results :
image.png
3.3 Log output location configuration
The previous introduction is to output logs to the console ,golang Of log The package also supports exporting logs to a file .log The package provided. func SetOutput(w io.Writer) function , Output the log to a file .
Log output location configuration
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
logFile, err := os.OpenFile(“./c.log”, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Panic(“ Opening the log file is abnormal ”)
}
log.SetOutput(logFile)
}
func main() {
log.Println(“println journal ”)
}
result : Log output to the current directory c.log In file
image.png
4、 Customize logger
log Package provides us with built-in functions , Let us customize logger. In terms of effect , Is to put the title 3 Standard log configuration in 、 Log prefix configuration 、 The log output location configuration is integrated into one function , Make the log configuration less cumbersome .
log The package provides func New(out io.Writer, prefix string, flag int) *Logger Function to implement custom logger.
Example
var logger *log.Logger
func init() {
logFile, err := os.OpenFile(“./c.log”, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Panic(“ Opening the log file is abnormal ”)
}
logger = log.New(logFile, “success”, log.Ldate | log.Ltime | log.Lshortfile)
}
func main() {
logger.Println(“ Customize logger”)
}
边栏推荐
- [electron] basic learning
- 树莓派(以及各种派)使用指南
- Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety
- Working at home is more tiring than going to work at the company?
- golang - new和make的区别
- Death of 5 yuan youkuang in Yuanqi forest
- EXCEL 打印设置公共表头
- Senior headhunting team manager: interviewed 3000 consultants, summarized and organized 8 commonalities (Mao Sheng)
- 通过 MQTT 检测对象和传输图像
- Fsnotify interface of go language to monitor file modification
猜你喜欢

Is the dog virtue training with a monthly salary of 30000 a good business?
![Technical implementation process of easycvr platform routing log function [code attached]](/img/cc/f4f81cbb72d2d43430a8d15bbbf27b.png)
Technical implementation process of easycvr platform routing log function [code attached]

Detect objects and transfer images through mqtt

发射,接收天线方向图

Discuz small fish game wind shadow legend business gbk+utf8 version template /dz game website template

Livox Lidar+海康Camera 基于loam的实时三维重建生成RGB彩色点云

Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板

【微服务|Sentinel】sentinel数据持久化

未能加载文件或程序集“CefSharp.Core.Runtime.dll”或它的某一个依赖项。 不是有效的 Win32 应用程序。 (异常来自 HRESULT:0x800700C1)

webService
随机推荐
Go语言fsnotify接口实现监测文件修改
UESTC (shenhengtao team) & JD AI (Mei Tao team) proposed a structured dual stream attention network for video Q & A, with performance SOTA! Better than the method based on dual video representation!
Discuz taobaoke website template / Dean taobaoke shopping style commercial version template
How to use RPA to achieve automatic customer acquisition?
【Vim】使用教程,常用命令,高效使用Vim编辑器
C# Winform 读取Resources图片
2022年PMP项目管理考试敏捷知识点(3)
Is the dog virtue training with a monthly salary of 30000 a good business?
Redis principle - string
量化交易入门教程
Senior headhunting team manager: interviewed 3000 consultants, summarized and organized 8 commonalities (Mao Sheng)
Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety
SQL Server 2016详细安装教程(附注册码和资源)
Swing UI——容器(一)
MySQL删除表后如何使ID从1开始
ABAP随笔-物料主数据界面增强-页签增强
Sentinel
seata
消除el-image图片周围间隙
Spark bug Practice (including bug: classcastexception; connectexception; noclassdeffounderror; runtimeexceptio, etc.)