Iyengar111 / NanoLog

Low Latency C++11 Logging Library
727 stars 186 forks source link

When log a char buff[size] veriable which create on stack, it will may log a invalid variable in write thread. #22

Open edigar007 opened 7 years ago

edigar007 commented 7 years ago

string_literal_t's constructor put the point of arg to m_cs, not a deep copy. when the arg is a veriable create on stack , or has ben changed, it will may log a invalid variable.

edwardlucas commented 3 years ago

This fix works for me.

Testing code below

#include <iostream>
#include <cstring>
#include "NanoLog.hpp"

extern const std::string VERSION = "this is a global std::string";

int main(int, char**) {
    nanolog::initialize(nanolog::GuaranteedLogger(), "log/", "nanologtest", 128);

    char s[64];
    strncpy(s, "this is a char", sizeof("this is a char"));
    LOG_INFO << "log a local char[]";
    LOG_INFO << s;
    LOG_INFO << "Log global string: '" << VERSION << "'";
}

result before fix (local char string always absent):

faund@bigwhite:~/Develop/tradingprojects/NanoLog/build/log$ more nanologtest.1.txt 
[2021-04-02 07:59:14.883606][INFO][139943388731200][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:12] log a local char[]
[2021-04-02 07:59:14.883614][INFO][139943388731200][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:13] 
[2021-04-02 07:59:14.883618][INFO][139943388731200][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:14] Log global string: 'this is a global std::string'

result after fix (local char string logged):

faund@bigwhite:~/Develop/tradingprojects/NanoLog/build/log$ more nanologtest.1.txt 
[2021-04-02 08:03:26.105471][INFO][139948852975424][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:12] log a local char[]
[2021-04-02 08:03:26.105481][INFO][139948852975424][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:13] this is a char
[2021-04-02 08:03:26.105483][INFO][139948852975424][/home/faund/Develop/tradingprojects/NanoLog/main.cpp:main:14] Log global string: 'this is a global std::string'