Very slow function!
You open and close file for each message. It's better to store open stream somewhere and call it when you need. For example you can create std::map< std::string, std::ofstream >.