i'm building api in php. api processes json messages third party api.
i want log invalid pretty printed json messages.
so did this:
error_log("test\n" . json_encode($json_string, json_pretty_print)); however, when @ logs, json string not pretty printed:
$ tailf error.log 2015-07-13 10:20:03: (mod_fastcgi.c.2701) fastcgi-stderr: test "{\"info\":{\"status\":200,\"msg\":\"ok\"},\"response\":{\"foo\":\"bar\"}" i want see like:
$ tailf error.log 2015-07-13 10:20:03: (mod_fastcgi.c.2701) fastcgi-stderr: test { "info": { "status": 200, "msg ": "ok" }, "response": { "foo": "bar" } } how can achive result?
error_log("test\n" . json_encode($json_string, json_pretty_print)); json_encode() not produce json: produce can read javascript. if give array or object, produce json; if give string, produce javascript string. , that’s you’re doing, that’s you’re getting.
to clear, $json_string string: (as far php concerned, it’s string; if passed same string javascript, interpreted object). pass through json_encode() , you’re going string (a string of doubly-encoded json).
json_pretty_print having no effect here, because you’re not producing json: you’re producing javascript see string.
savvy?
so need (a) turn $json_string php array, , (b) reencode json, time using json_pretty_print flag.
$log_array = json_decode($json_string, true); $json_pretty_string = json_encode($log_array, json_pretty_print); error_log('test' . php_eol . $json_pretty_string); rather converting php array , json, better add json_pretty_print flag wherever you’re getting $json_string in first place, if possible.
alternatively, log $json_string directly (no need encode it: it’s string, can pass error_log() is), , worry prettifying when need read logs. make logs considerably smaller.
Comments
Post a Comment