Ruby 对于多进程或者多线程 Logger 类是否是安全的?

nameofhsw · May 13, 2015 · Last by luikore replied at May 13, 2015 · 2460 hits

在使用 Logger 类进行日志管理的时候,多进程以及多线程运行情况下,创建多个日志类对同一个日志文件进行操作,是否是安全的? 如果是,那么是通过什么实现的呢?文件锁? 如果不是,哪有没有安全的日志类,或者通过自行增加 mutex 来解决吗? 在网上查了很多 Logger 相关的资料,但是没发现有用的,所以求助下各位,感谢!

在 Linux 一直是安全的,因为

  • Logger IO 是 sync 的不 buffer
  • Logger::LogDevice#write 用了 mutex 保证线程安全
  • Linux 的 write 函数是原子的保证进程安全

对 log rotation, Ruby 2.1 之后是安全的,因为

  • 现在 logger 打开 log 时会调用文件锁 logdev.flock(File::LOCK_EX)

信息来源:源代码和 http://b.hatena.ne.jp/entry/www.slideshare.net/sonots/rubylogger-rubyconf-20131109

You need to Sign in before reply, if you don't have an account, please Sign up first.