英文:
Avoid messy output when writing to STDOUT from goroutines
问题
当向stdout
或日志写入时,如何确保来自多个goroutine的输出不会混乱?
例如,确保输出如下所示:
Routine 1 found 1235 entries
Routine 3 found 999 entries
Routine 2 found 24 entries
而不是像这样:
Routine 1 fouRoutine 3 found 999 entries
nd 1235 entriRoutine 2 found 24 entries
es
我的意思是一个goroutine的输出不会与另一个同时写入。
也就是说,是否有一种库或标准方法可以在输出周围获取一个信号量?
英文:
When writing to stdout
or a log, how can I make sure that the output from several goroutines
aren't messing up the output?
e.g. make sure the output will be like this
Routine 1 found 1235 entries
Routine 3 found 999 entries
Routine 2 found 24 entries
and NOT like this
Routine 1 fouRoutine 3 found 999 entries
nd 1235 entriRoutine 2 found 24 entries
es
I mean the output from one goroutine is not writing at the same time as another
i.e. is there a library or a standard way to get a semaphore around the output?
答案1
得分: 6
使用log
包进行日志记录。从log.Logger
开始:
> Logger表示一个活动的日志对象,它生成输出行到一个io.Writer。每个日志操作都会调用Writer的Write方法。一个Logger可以同时从多个goroutine中使用;它保证对Writer的访问进行序列化。
通常不建议在多个goroutine中使用fmt
包进行日志记录。
如果时间(锁的同步)是一个问题,可以在日志语句前加上go
:
go log.Println("some log")
但请注意,日志输出可能会(几乎肯定会)延迟。
英文:
Use the log
package for logging. From log.Logger
:
> A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.
The fmt
package is generally not safe to use with more than one goroutine.
If time (synchronizing of lock) is of concern, prepend the log statement with go
:
go log.Println("some log")
Note however, that the log output then may be (most certainly) delayed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论