在使用goroutines写入标准输出时,避免输出混乱。

huangapple go评论126阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年12月11日 20:12:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/20518829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定