3

I am trying to use a severity channel logger but I hit the problem with BOOST_LOG_SEV not being a const method -- I'm thinking because of both open_record() and push_record()

This will basically force me to make all methods in my classes not const because they want to write out to their loggers. I can't really afford to do that -- so I'm restricted to global loggers at the moment.

In my current implementation, each class has a logger with the class name as the channel (initialized in their constructors), and it issues log messages at any point with BOOST_LOG_SEV(this->logger, level)

I'd love to hear the reason behind the non-constness and if my design is not the intended for Boost::Log.

Carneiro
  • 3,479
  • 5
  • 24
  • 36
  • Boost is open-source afterall, so you could simply consult the source code. I guess that would be faster than asking a question and waiting on answers. – Alexander Shukaev Nov 24 '13 at 07:53
  • They cannot be non-const because they change state. If the loggers are thread safe though then they are a perfect example of where you should use the mutable keyword. Loggers are non-const, thread safe members that do not affect the state of the object. – John5342 Nov 24 '13 at 08:12
  • would there be a better design then? Making the loggers class members is out of the question since I'd have to make every method non-const. – Carneiro Nov 24 '13 at 08:19
  • 2
    Make the loggers mutable class member `mutable SomeLoggerType my_logger;`. Then you will be able to modify it in non-const members. This is precisely what mutable was meant for. – John5342 Nov 24 '13 at 08:23
  • Ah, that works, thanks! (and I'm happy to make it an answer if you type it) But isn't this whole process of using a mutable member in the class in const methods a big "code smell" ? – Carneiro Nov 24 '13 at 08:43
  • It is a code smell if changing the mutable member changes your objects logical state (although in c++11 it's just as much about thread safety). – John5342 Nov 24 '13 at 08:57

1 Answers1

5

The loggers cannot be const because they change thier own state. If the loggers are thread safe and don't change the logical state of your object then they are a perfect example of where you should use the mutable keyword.

Make the loggers mutable class member mutable SomeLoggerType my_logger;. Then you will be able to modify it in const members. This is precisely what mutable was meant for.

As to your comment about mutable being a bad code smell, mutable is an escape hatch for precisely this kind of purpose. Mutable is fine when you are actually not modifying the logical state of your object (and in c++11 internally synchronised). Another perfectly good example of mutable usage is caching.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
John5342
  • 1,129
  • 1
  • 10
  • 13
  • Thanks Igor for the edit. That will teach me to write a quick answer on the small screen of a phone. – John5342 Nov 24 '13 at 17:37