Add connection identifier to log lines for multi-client applications
Problem
When running multiple AMQP clients in a single application, it was impossible to distinguish which log lines belonged to which connection. This made debugging and monitoring difficult in production environments with multiple concurrent connections.
Solution
Added a unique connection identifier to all log lines using Crystal's Log.context feature. The identifier is:
-
For TCP/SSL connections: The local port number (e.g.,
54321) - For UNIX sockets/WebSockets: The object ID
Using the local port number (as suggested in #issue-comment) provides an excellent identifier because:
- It's unique per TCP connection on the host
- Easy to correlate with network debugging tools (tcpdump, netstat, etc.)
- Visible in server logs and management interfaces
- Requires no additional configuration
Implementation Details
The connection identifier is:
- Extracted during connection initialization from the socket's local address
- Stored in the
@connection_idinstance variable - Set in the log context for all logging operations:
- Incoming frame processing (
read_loop) - Outgoing frame writing (
unsafe_write) - Connection lifecycle events (
close)
- Incoming frame processing (
Example Output
Before:
DEBUG - recv Frame::Basic::Deliver(...)
DEBUG - sent Frame::Basic::Ack(...)
After (with two connections):
DEBUG - recv Frame::Basic::Deliver(...) connection_id=54321
DEBUG - sent Frame::Basic::Ack(...) connection_id=54321
DEBUG - recv Frame::Basic::Deliver(...) connection_id=54322
DEBUG - sent Frame::Basic::Ack(...) connection_id=54322
Testing
- Added unit test to verify
@connection_idis properly set - Created example script (
examples/connection_identifier_test.cr) demonstrating the feature with multiple connections - All existing tests continue to pass
Fixes #[issue-number]
Original prompt
This section details on the original issue you should resolve
<issue_title>Add some kind of identifier to log lines</issue_title> <issue_description>If you have multiple amqp-clients in one application you can't tell which logs belong to which clients. It would be good with some kind of identifier that follows one client's log. Maybe just the
#object_idfor theConnection.</issue_description>Comments on the Issue (you are @copilot in this section)
@carlhoerberg Src port should be unique between client connections?
Fixes cloudamqp/amqp-client.cr#62
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.