diff --git a/src/babylon/logging/log_stream.cpp b/src/babylon/logging/log_stream.cpp index 8c33fcd..303f8af 100644 --- a/src/babylon/logging/log_stream.cpp +++ b/src/babylon/logging/log_stream.cpp @@ -25,12 +25,15 @@ void LogStream::do_end() noexcept {} DefaultLogStream::DefaultLogStream() noexcept : #if __clang__ || BABYLON_GCC_VERSION >= 50000 - LogStream {*::std::cerr.rdbuf()} { -} + LogStream {*::std::cerr.rdbuf()} #else // !__clang__ && BABYLON_GCC_VERSION < 50000 - LogStream(*::std::cerr.rdbuf()) { -} + LogStream(*::std::cerr.rdbuf()) #endif // !__clang__ && BABYLON_GCC_VERSION < 50000 +{ + // Ensure std::cerr is initialized + ::std::ios_base::Init(); + rdbuf(::std::cerr.rdbuf()); +} ::std::mutex& DefaultLogStream::mutex() noexcept { static ::std::mutex mutex; @@ -61,14 +64,17 @@ void DefaultLogStream::do_end() noexcept { NullLogStream::NullLogStream() noexcept : #if __clang__ || BABYLON_GCC_VERSION >= 50000 - LogStream {s_buffer} { + LogStream {buffer()} { } #else // !__clang__ && BABYLON_GCC_VERSION < 50000 - LogStream(s_buffer) { + LogStream(buffer()) { } #endif // !__clang__ && BABYLON_GCC_VERSION < 50000 -NullLogStream::Buffer NullLogStream::s_buffer; +NullLogStream::Buffer& NullLogStream::buffer() noexcept { + static Buffer static_buffer; + return static_buffer; +} // NullLogStream end //////////////////////////////////////////////////////////////////////////////// diff --git a/src/babylon/logging/log_stream.h b/src/babylon/logging/log_stream.h index 3b571f6..5d77a0f 100644 --- a/src/babylon/logging/log_stream.h +++ b/src/babylon/logging/log_stream.h @@ -175,7 +175,8 @@ class NullLogStream : public LogStream { private: class Buffer; - static Buffer s_buffer; + + static Buffer& buffer() noexcept; }; //////////////////////////////////////////////////////////////////////////////// diff --git a/test/logging/BUILD b/test/logging/BUILD index 3b921b6..5cc5576 100644 --- a/test/logging/BUILD +++ b/test/logging/BUILD @@ -74,6 +74,17 @@ cc_test( ] ) +cc_test( + name = 'test_log_statically', + srcs = ['test_log_statically.cpp'], + copts = BABYLON_COPTS, + linkstatic = True, + deps = [ + '//:logging_logger', + '@com_google_googletest//:gtest_main', + ] +) + cc_test( name = 'test_rolling_file_object', srcs = ['test_rolling_file_object.cpp'], diff --git a/test/logging/test_log_statically.cpp b/test/logging/test_log_statically.cpp new file mode 100644 index 0000000..6a18d65 --- /dev/null +++ b/test/logging/test_log_statically.cpp @@ -0,0 +1,9 @@ +#include "babylon/logging/logger.h" + +// Do BABYLON_LOG at very begining of the program. +// Check whether log system is ensured to be ready in default state +__attribute__((init_priority(101))) static struct StaticallyInitialized { + StaticallyInitialized() { + BABYLON_LOG(INFO) << "log in static initialize stage is fine"; + } +} statically_initialized_instance;