首页 > 其他分享 >Go - Using Log Levels

Go - Using Log Levels

时间:2023-09-29 18:00:14浏览次数:30  
标签:00 log Some debug Levels Go Using event happened

Examples of log levels from high to low are:
• Fatal
• Error
• Warn
• Info
• Debug

To set up log levels for your logs, you can add the level to each line of the log. The most straightforward way of doing this is to use the SetPrefix function:

log . SetPrefix ( "INFO  " ) 
log . Println ( "Some  event  happened" )

If you call the SetPrefix function with the log level as the prefix, you will set the log level at the beginning of the line:

INFO 2022/01/26 00:48:15 Some event happened

Of course, the problem is that each time you want to add a log line with a different log level from the previous line, you need to call SetPrefix again. That is not a feasible solution.

Another method is to create new loggers upfront, with each logger representing a single log level:

var   ( 
      info    * log . Logger 
      debug   * log . Logger 
) 

func   init ()   { 
      info   =   log . New ( os . Stderr ,   "INFO\t" ,   log . LstdFlags ) 
      debug   =   log . New ( os . Stderr ,   "DEBUG\t" ,   log . LstdFlags ) 
}

To do this, you use the New function, which returns a logger, but you can also set the prefix and the fields to add to the log.
All you need to do to log events with different log levels is to use the appropriate loggers:

info . Println ( "Some  informational  event  happened" ) 
debug . Println ( "Some  debugging  event  happened" )

This is what will appear on the screen:

INFO	 2022/01/26  00:53:03  Some  informational  event  happened
DEBUG	 2022/01/26  00:53:03  Some  debugging  event  happened

You can also turn off logging for specific log levels to reduce the logfile size. For example, when you’re developing the program you can log debug events, but once you run in production, you no longer want to do that. A common practice is to use environment variables to indicate if you are running in development or production.

Retrieving the environment variable in Go is simple. You can use the os.Getenv function, passing it the environment variable name, and you will get the environment variable value. Using the same previous example, let’s set the ENV environment
variable to production :

$  export  ENV=production

If you run this code, you will see that the debug event is not printed:

info . Println ( "Some  informational  event  happened" ) 
if   os . Getenv ( "ENV" )   !=   "production"   { 
      debug . Println ( "Some  debugging  event  happened" ) 
}

If you switch to the development environment, the debug event is printed again.

At the start of this recipe, you learned that one of the reasons to use log levels is to prioritize and filter off certain log levels. You can do this easily with a Unix - based system using the grep command.
Say you have a file named logfile.log with the following entries:
INFO 2023/01/06 00:21:32 Some informational event happened

DEBUG 2023/01/06 00:21:32 Some debugging event happened
INFO 2023/01/06 00:21:35 Another informational event happened
WARN 2023/01/06 00:23:35 A warning event happened
WARN 2023/01/06 00:33:11 Another warning event happened
ERROR 2023/01/06 00:33:11 An error event happened

You want to look at all error events first so you can use grep to filter out only error events:

$ grep "^ERROR" logfile.log

What if you want to see all log events except for debug events? You can just exclude the debug events using the v flag in grep :

$ grep - v "^DEBUG" logfile.log

Using grep is only the beginning. grep is a powerful tool, but there are many other log analysis tools you can use.

标签:00,log,Some,debug,Levels,Go,Using,event,happened
From: https://www.cnblogs.com/zhangzhihui/p/17737145.html

相关文章

  • CF1425F Flamingoes of Mystery 题解
    题目传送门前置知识前缀和&差分解法令\(sum_k=\sum\limits_{i=1}^{k}a_k\)。考虑分别输入\(sum_2\simsum_n\),故可以由于差分知识得到\(a_i=sum_i-sum_{i-1}(3\lei\len)\),接着输入\(a_2+a_3\)的值从而求出\(a_2=sum_3-a_3,a_1=sum_2-a_2\)。同时因为是交互题,记......
  • Go - Logging to File
    Problem: Youwanttologeventstoalogfileinsteadofstandarderror.Solution: UsetheSetOutputfunctiontosetthelogtowritetoafile. YouuseSetOutputtoredirecttheoutputtoafile.file,err:=os.OpenFile("app.log"......
  • Go - Change What Is Being Logged by the Standard Logger
    Problem: Youwanttochangewhatthestandardloggerlogs.Solution: UsetheSetFlagsfunctiontosetflagsandaddfieldstoeachlogline. Thedefaultbehaviorofthestandardloggeraddsthedateandtimefieldstoeachlineofthelog. Thelogpac......
  • Go - logging
    Thelogpackageprovidesseveralfunctionsthatallowyoutowritelogs.Inparticular,therearethreesetsoffunctions:Print•PrintsthelogstotheloggerFatal•Printstotheloggerandcallsos.Exitwithanexitcodeof1Panic•Printstothelo......
  • Go - Inspecting Errors
    Problem: Youwanttocheckforspecificerrorsorspecifictypesoferrors.Solution: Usetheerrors.Isanderrors.Asfunctions.Theerrors.Isfunctioncomparesanerrortoavalueandtheerrors.Asfunctionchecksifanerrorisofaspecifictype. Us......
  • MongoDB playground All In One
    MongoDBplaygroundAllInOneMongoDBREPLhttps://mongoplayground.net/db={"teacher":[{"_id":ObjectId("64fee9b54273ac2234441225"),"teacherid":ObjectId("64f1d72a4331bc8fc4c5930f"......
  • 关于一个django工程如何与达梦数据库连接的全程总结
    关于一个django工程如何与达梦数据库连接的全程总结目录1.达梦数据库的安装(win、图形化工具)2.DM管理工具的基本使用:表空间的建删用户的管理模式的建删表的创建、删除、查看3.Django项目接入dm数据库settings的database配置解释器中的相关包dmPython的编译※环境准备正式编......
  • Go - Wrapping an Error with Other Errors
    Problem: Youwanttoprovideadditionalinformationandcontexttoanerroryoureceivebeforereturningitasanothererror.Solution: Wraptheerroryoureceivewithanothererroryoucreatebeforereturningit. Thereareacoupleofwaystowraperr......
  • Go - Creating Customized Errors
    Problem: Youwanttocreatecustomerrorstocommunicatemoreinformationabouttheerrorencountered.Solution: Createanewstring-basederrororimplementtheerrorinterfacebycreatingastructwithanErrormethodthatreturnsastring. Therea......
  • Go 语言概述
    本文主要包含以下内容:为什么需要一门新的语言Go 语言基本介绍Go 的发展历程Go 应用领域o 语言基本介绍在上述背景下,谷歌公司于 2009 年推出了新一代的编程语言 Go。提起 Go 语言的出身,我们就必须将我们饱含敬意的眼光投向持续推出惊世骇俗成果的贝尔实验室。贝尔实验室已......