plog icon indicating copy to clipboard operation
plog copied to clipboard

Capture stdout and redirect to plog

Open Ry-Kode opened this issue 2 years ago • 11 comments

Hello,

Would it be possibe to redirect stderr so that stuff written to stderr is written to the log?

Thanks!

Ry-Kode avatar Oct 26 '23 19:10 Ry-Kode

Hi @Ry-Kode !

Could you give some more details? As there could be different solutions.

SergiusTheBest avatar Oct 30 '23 16:10 SergiusTheBest

Hello Sergius,

I'm not qutie sure what kind of details I can provide. Let me explain my use case: in my project I'm using your PLOG lib (thanks again for this!!) to create a rolling logfile. I'm also using some third party libraries which generate output that is written to stderr (and sometimes stdout). I'm looking for a way to 'capture' this output and save it to the PLOG rolling log file.

Thank you

Ry-Kode avatar Nov 04 '23 13:11 Ry-Kode

Can you recompile those libraries?

SergiusTheBest avatar Nov 04 '23 14:11 SergiusTheBest

So you can just add #define cerr cerr; PLOGI and include plog?

SergiusTheBest avatar Nov 04 '23 14:11 SergiusTheBest

Yes, that would be one option. Unfortuantely there are some libraries for which I do not have access to the source code so I cannot recompile them.

Ry-Kode avatar Nov 06 '23 13:11 Ry-Kode

Hello Sergius, Can you give recommendations on best approach for the libraries which I cannot recompile? Thank you

Ry-Kode avatar Nov 19 '23 19:11 Ry-Kode

@Ry-Kode Are they static libs (.lib) or dynamic libs (.dll)?

SergiusTheBest avatar Nov 19 '23 20:11 SergiusTheBest

Static libs (.lib)

Ry-Kode avatar Nov 20 '23 09:11 Ry-Kode

You can try the following approach:

union
{
    struct
    {
        int readPipe;
        int writePipe;
    };
    int pipeHandles[2];
} pipes;

_pipe(pipes.pipeHandles, 0, O_TEXT);

_dup2(pipes.writePipe, _fileno(stderr));

auto pipeFuture = std::async(launch::async, [&]()
{
    std::array<char, 0x800> buf{};

    for(;;)
    {
        int bytesRead = _read(pipes.readPipe, buf.data(), static_cast<int>(buf.size()));
        if (bytesRead <= 0)
        {
            break;
        }

        buf[bytesRead] = 0;
        LOGV << buf.data();
    }
});

std::cerr << "test test";

_close(pipes.writePipe);
_close(_fileno(stderr));

It may work for your setup. But there is no guarantee.

SergiusTheBest avatar Nov 21 '23 18:11 SergiusTheBest

Thank you for the snippet Sergius. However, It looks like this is Windows-only. _pipe, _dup2 etc are not supported on Posix. Do you an equivalent for Linux?

Ry-Kode avatar Nov 21 '23 21:11 Ry-Kode

Posix is the same, just without the underscore.

SergiusTheBest avatar Nov 21 '23 22:11 SergiusTheBest