Get unique worker/thread/process/request ID in PHP

cheesus picture cheesus · May 1, 2012 · Viewed 8.6k times · Source

In multi-threaded environments (like most web platforms) I often include some sort of thread ID to the logs of my apps. This enables me to tell exactly what log entry came from which request/thread, when there are multiple requests at once which are simultaneously writing to the same log.

In .NET/C#, this can be done by the formatters of log4net, which by default include the current thread's ManagedThreadId (a number) or Name (a given name). These properties uniquely identify a thread (see for example: How to log correct context with Threadpool threads using log4net?

In PHP, I have not found anything similar (I asked Google, PHP docs and SO). Does it exist?

Answer

gilm picture gilm · Mar 19, 2014

Up until recently, I used apache_getenv("UNIQUE_ID"), and it worked perfectly with a crc32 or another hash function.

Nowadays I'm just using the following, in order to remove dependency on Apache and this mod.

$uniqueid = sprintf("%08x", abs(crc32($_SERVER['REMOTE_ADDR'] . $_SERVER['REQUEST_TIME'] . $_SERVER['REMOTE_PORT'])));

It's unique enough to understand which logs belong to which request. If you need more precision, you can use other hash functions.

Hope this helps.