How to create a Log in C++?

2019-03-20 17:48发布

I want to print lots of debug log prints in C++. Is there a built-in library that will allow me to turn on/off these prints without commenting them out as I do today (i.e., let the user use a -print_log/-debug flag)?

EDIT: third party loggers will be welcomed.

Please include a short example of how to do this.

标签: c++ logging
6条回答
甜甜的少女心
2楼-- · 2019-03-20 18:09

log4cpp works really well.

There is a BOOST log although it is not part of the official set of libraries.

查看更多
Anthone
3楼-- · 2019-03-20 18:12

You can use syslog

查看更多
4楼-- · 2019-03-20 18:17
聊天终结者
5楼-- · 2019-03-20 18:21

There is no built-in library. There are third-party libraries, or you could implement your own without too much effort. One decent way to do this is to have a logging function that accepts a FILE*, that can be stdout or /dev/null (or equivalent), or a file, etc.

Since you mention that it's C++, you can also do it with streams, accepting an ostream& that can be cout, cerr, a file, etc.

查看更多
等我变得足够好
6楼-- · 2019-03-20 18:22

One of approaches: write all messages to std::wclog. It's similar to std::wcout and can be redirected in the same way.

Not sure about its multithread safety, or other features, but it seems to be the simplest way - it already exists.

查看更多
放我归山
7楼-- · 2019-03-20 18:33

If you're using Boost, consider using the proposed Boost.Log library. It's not yet part of the official Boost release, but I've found it to be quite good. Manually integrating it into the Boost build process was a little challenging though.

查看更多
登录 后发表回答