making log file

hey, i want to be able to store every log that happens in its own text file in a folder called "logs" how could i store all of the displayed data till the stop in its own text file for each launch.

i need this for debugging purposes
which one is the correct code?
please paste it
Accepted answer is a boost class. If you do not have boost, use next answer.
> ... in its own text file for each launch.

Add a time stamp to the name of the log file.
Crude example (among other things, does not handle order of initialisation issues if log is used before main):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//////// header log.h ///////////
#include <string>
#include <fstream>

namespace log
{
    extern const std::string path ;
    extern std::ofstream out ;
    void flush() ;
}

//////// implementation log.cpp ///////////
// #include "log.h"
#include <ctime>

namespace log
{
    void flush() { out.flush() ; }

    namespace // detail
    {
        std::string time_stamp()
        {
            const auto now = std::time(nullptr) ;
            char cstr[256] {};
            return std::strftime( cstr, sizeof(cstr), "%Y%m%d_%H%M%S", std::localtime(&now) ) ? cstr : "" ;
        }

        std::string path_to_session_log_file()
        {
            static const std::string log_dir = "/tmp/log/" ;
            static const std::string log_file_name = "log.txt" ;
            return log_dir + time_stamp() + '_' + log_file_name ;
        }
    }

   const std::string path = path_to_session_log_file() ;
   std::ofstream out = std::ofstream( path );
}

//////////// usage main.cpp ///////////////
// #include "log.h"
#include <iostream>

int main()
{
    std::cout << "path: " << log::path << '\n' ;
    log::out << "this is a test\n" ;
    log::out << "this is another test\n" ;
    log::flush() ;
    std::cout << "\n--------------------\n" << std::ifstream( log::path ).rdbuf() ;
    
    log::out << "this is the third test\n" ;
    log::flush() ;
    std::cout << "\n--------------------\n" << std::ifstream( log::path ).rdbuf() ;
}

http://coliru.stacked-crooked.com/a/ba5ccf04eb522e27
Topic archived. No new replies allowed.