Search code examples
c++boostboost-log

How to achieve thread safety in Boost log


I have a multi thread application where I'd like to use boost-log. I'm using boost 1.81.

To log I use macro

BOOST_LOG_TRIVIAL

Here where I configure boost-log:

logging::register_simple_formatter_factory<logging::trivial::severity_level, char>("Severity");
logging::register_simple_filter_factory<logging::trivial::severity_level, char>("Severity");

std::ifstream file("log.config");
logging::init_from_stream(file);
logging::add_common_attributes();

Here is log.config content:

[Core]
DisableLogging=false
#Filter="%Severity% > info"

# Sink settings sections
[Sinks.File]
# Sink destination type
Destination=TextFile

# Sink-specific filter. Optional, by default no filter is applied.
Filter="%Severity% > trace"

# Formatter string. Optional, by default only log record message text is written.
Format="[%TimeStamp%] %Message%"

FileName="Log_%d%m%y_%3N.log"
Target="logs"

RotationSize= 5242880 # 5MB

# The flag shows whether the sink should be asynchronous
Asynchronous=false

# Enables automatic stream flush after each log record.
AutoFlush=true

The output log file has corrupted lines, or truncated/overlapped lines as follow:

corrupted line

truncated and overlapped lines

How can I achieve a log file without these problems?

I assumed boost would handle concurrency, there is a way to enable it?


Solution

  • I tried to reproduce my problem in a minimal reproducible example. I was not able to reproduce the problem.

    Looking deeply in my code I found out my singleton implementation had a bug and the boost log configuration was performed twice:

    logging::register_simple_formatter_factory<logging::trivial::severity_level, char>("Severity");
    logging::register_simple_filter_factory<logging::trivial::severity_level, char>("Severity");
    
    std::ifstream file("log.config");
    logging::init_from_stream(file);
    logging::add_common_attributes(); 
    

    The double boost configuration produce the errors described above. I added this as answer to guide someone who will have the same errors of corrupted/overlapped/truncated lines in log file.