Asynchronous thread-safe logging in C++

后端 未结 5 445
南方客
南方客 2021-02-04 04:04

I\'m looking for a way to do asynchronous and thread-safe logging in my C++ project, if possible to one file. I\'m currently using cerr and clog for th

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 05:08

    This is VERY possible and practical. How do I know? I wrote exactly that at my last job. Unfortunately (for us), they now own the code. :-) Sadly, they don't even use it.

    I intend on writing an open source version in the near future. Meanwhile, I can give you some hints.

    1. I/O manipulators are really just function names. You can implement them for your own logging class so that your logger is cout/cin compatible.
    2. Your manipulator functions can tokenize the operations and store them into a queue.
    3. A thread can be blocked on that queue waiting for chunks of log to come flying through. It then processes the string operations and generates the actual log.

    This is intrinsically thread compatible since you are using a queue. However, you still would want to put some mutex-like protection around writing to the queue so that a given log << "stuff" << "more stuff"; type operation remains line-atomic.

    Have fun!

提交回复
热议问题