0

I use function error_log() in my PHP script. If several instances of the script run concurrently, all of them will write into the same log file, and their messages will intermingle. I need to tell their records one from another.

I would be able to do so, if I had a unique ID for each running script, say, $script_id, so I would output a log message $message like this:

error_log($script_id . ': ' . $message);

but can I retrieve such a unique ID anywhere?

UPDATE 1: Or is there a better way of logging for these circumstances?

UPDATE 2: It would be interesting to retrieve the process ID of the process in which the script runs.

Alex K
  • 31
  • 7
  • You can just make a random ID. [Here's a google search for "PHP random string"](https://www.google.dk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=php%20random%20string). "Yes, but it isn't UNIQUE!!!". Sure, but the risk that duplicate random strings will occur at the same time is minimal. If you really wish, keep a DB table of ID's and when you create a unique ID verify that it isn't in the DB. – h2ooooooo Oct 22 '14 at 12:07
  • Why not just use Unix time? – James Hunt Oct 22 '14 at 12:07
  • with `session`, you can use the `session_id()`; – vaso123 Oct 22 '14 at 12:08
  • @JamesHunt 5 requests/script instances in a second would get the same ID which is not what he wants. – h2ooooooo Oct 22 '14 at 12:08
  • @h2ooooooo A random number may be good, if it is random enough. – Alex K Oct 22 '14 at 12:09
  • @AlexK I've had success with 5 random A-Z0-9 characters before. They're easy to distinguish (numbers are not as much) and the risk of a concurrent collision is `1 / 52521875`. If you wish, you can simply use 6 characters and up that to `1 / 1838265625`. – h2ooooooo Oct 22 '14 at 12:10
  • Yes, @JamesHunt, the time is only in the one-second resolution. – Alex K Oct 22 '14 at 12:11
  • why not append datetime now microtime to it.. – Pogrindis Oct 22 '14 at 12:20
  • you can create a random id from a big random number and with a microtime ctypted with md5. but why `session_id();` is not good for you? – vaso123 Oct 22 '14 at 12:25
  • @lolka_bolka, session_id() is good, if opening a session is not detrimental in any way. Please put your suggestion as an answer. – Alex K Oct 22 '14 at 12:47
  • opening a session is not detrimental, but i read this: http://stackoverflow.com/questions/138670/how-unique-is-the-php-session-id so i do not suggest you to use it. – vaso123 Oct 22 '14 at 12:50

1 Answers1

0

You can use the php function uniqid :

$script_id = uniqid();
error_log($script_id . ': ' . $message);
Veve
  • 6,643
  • 5
  • 39
  • 58