首页 > 其他分享 >Go - Logging to File

Go - Logging to File

时间:2023-09-29 15:22:07浏览次数:42  
标签:SetOutput Logging File err write file Go os log

Problem: You want to log events to a logfile instead of standard error.


Solution: Use the SetOutput function to set the log to write to a file.

 

You use SetOutput to redirect the output to a file.

file ,   err   :=   os . OpenFile ( "app.log" ,   os . O_APPEND | os . O_CREATE | os . O_WRONLY ,   0644 ) 
if   err   !=   nil   { 
      log . Fatal ( err ) 
} 
defer   file . Close ()

You call SetOutput with the file as the parameter, then continue to log:

log . SetOutput ( file )
log . Println ( "Some event happened" )

The output will be written to the app.log file instead of the screen.

 

As you probably realize from the code, setting up the logs to be written to file should be done once. What if you want to write to the screen and the file simultaneously? You could reset the log output each time (don’t do this) or maybe create two loggers, one for standard error and another for a file, then call the loggers in separate statements.
Or you can use Go’s MultiWriter function in the io package, which creates a writer that duplicates its writes to all the provided writers:

file ,   err   :=   os . OpenFile ( "app.log" ,   os . O_APPEND | os . O_CREATE | os . O_WRONLY ,   0644 ) 
if   err   !=   nil   { 
      log . Fatal ( err ) 
} 
defer   file . Close () 
writer   :=   io . MultiWriter ( os . Stderr ,   file ) 
log . SetOutput ( writer ) 
log . Println ( "Some  event  happened" ) 
log . Println ( "Another  event  happened" )

Doing this will write to both the screen and the file simultaneously. In fact, you can write to more than two writers!

 

标签:SetOutput,Logging,File,err,write,file,Go,os,log
From: https://www.cnblogs.com/zhangzhihui/p/17737021.html

相关文章

  • 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 语言的出身,我们就必须将我们饱含敬意的眼光投向持续推出惊世骇俗成果的贝尔实验室。贝尔实验室已......
  • 【代码分享】如何用go语言做一个简单的爬虫工具
    之前跟大家分享过一个简单的php做的爬虫,今天给大家带来一个使用golang来制作的一个简单的爬虫工具!大家看在中秋节我还更文的份上大家多评论转发收藏一下哟~也祝大家中秋节快乐安康~*使用colly来做一个简单的爬虫#安装collygogetgithub.com/gocolly/colly编写代码package......
  • Go - Simplifying Repetitive Error Handling
    Problem: Youwanttoreducethenumberoflinesofrepetitiveerror-handlingcode.Solution: Usehelperfunctionstoreducethenumberoflinesofrepetitiveerror-handlingcode. OneofthemostfrequentcomplaintsaboutGo’serrorhandling,especi......