Search code examples
c++loggingtimespdlog

How to print time in log file using spdlog


How should I print the time when opening and closing a log file?

Here:

#include <fmt/core.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>


int main( )
{
    spdlog::file_event_handlers handlers;

    handlers.after_open   = []( const spdlog::filename_t filename, std::FILE* const stream )
                            { fmt::print( stream, "\nFile '{}': Logging started...\n\n", filename ); };

    handlers.before_close = []( const spdlog::filename_t filename, std::FILE* const stream )
                            { fmt::print( stream, "\nFile '{}': Logging finished.\n", filename ); };

    auto logger { spdlog::basic_logger_st( "basic_logger", "logs/basic-log.txt", true, handlers ) };
}

I want to log the start and end time of logging. Those two callbacks that are passed to the file logger should be able to include the current time in their print statements. Does spdlog have a way for doing this?


Solution

  • Add the time info explicitly in your callback function:

    #include <fmt/chrono.h>
    
    handlers.after_open = []( const spdlog::filename_t filename, std::FILE* const stream ) { 
      auto now = std::chrono::system_clock::now();
      fmt::print( stream, "\nFile '{}': Logging started {}\n\n", filename, now ); 
    };
    

    This should render the time output in this form: 2021-07-04 18:03:09