KLogger icon indicating copy to clipboard operation
KLogger copied to clipboard

Invalid JSON

Open ryan-nash opened this issue 8 years ago • 6 comments

The method described in the README to get pure JSON appears to output invalid JSON.

This is the example output from the docs:

{"datetime":"2015-04-16 10:28:41.186728","logLevel":"INFO","message":"Message content","context":"{"1":"foo","2":"bar"}"}

It doesn't pass a JSON validator and causes json_decode() to return null.

This is valid JSON, without quotes around the context value:

{"datetime":"2015-04-16 10:28:41.186728","logLevel":"INFO","message":"Message content","context":{"1":"foo","2":"bar"}}

At the moment I'm just using Regex to remove the quotes.

ryan-nash avatar Oct 11 '17 00:10 ryan-nash

Well then, guess we'll have to fix this one. Thanks for the report!

katzgrau avatar Oct 12 '17 00:10 katzgrau

It seems like there was no update since october 2017, but the problem is still here.

Thank you for solving this annoying problem !

flavienbwk avatar Jul 09 '18 14:07 flavienbwk

@flavienbwk Sorry to sound negative here but perhaps you could consider fixing the issue? Any Open Source project stands and falls with the help of others creating a Pull Request to help resolve any open bugs or issues that are found.

The negative tone of "Thank you for solving this annoying problem !" isn't really necessary since you could easily try and resolve the issue and create a PR for this yourself ;)

onno-vos-dev avatar Jul 09 '18 14:07 onno-vos-dev

Oh, didn't want to sound negative, sorry for this! (Actually just wanted to thank you for trying to solve this 😄 ).

flavienbwk avatar Jul 09 '18 14:07 flavienbwk

Hint, I believe the problem exists in: https://github.com/katzgrau/KLogger/blob/master/src/Logger.php#L277 ;)

onno-vos-dev avatar Jul 09 '18 14:07 onno-vos-dev

Actually the sample code is incorrect. The following sample code will work to produce valid per-line JSON

        $contextValue = '{context}';
        $logFormat = json_encode([
            'datetime' => '{date}',
            'logLevel' => '{level}',
            'message' => '{message}',
            'context' => $contextValue,
        ]);
        $logFormat = str_replace("\"$contextValue\"", $contextValue, $logFormat);

The reason why this is needed is because the string '{context}' gets JSON encoded to double quotes. So after the logFormat has been serialized you should need to remove the double quotes that were added by the JSON serialization.

gabema avatar Oct 23 '18 23:10 gabema