Parsing Mosquitto MQTT Broker Log Messages: Understanding 'New Connection' Messages

Abstract: Extract the client identifier from Mosquitto connection logs by parsing the seventh space-delimited field to handle both named IDs and anonymous clients.

Created: 2026-08-22 by

Mosquitto logs use the log_type directive to control output, not log_level. The standard format for a new connection is New client connected from IP:port as ID (c0, k60). To parse this reliably in Bash or Python, extract the client identifier from the fifth field after splitting by spaces, while noting that anonymous clients appear as "anonymous" rather than a UUID.

Configuring Log Output Types

To understand how to parse these messages, you must first ensure Mosquitto is configured to emit them. A common misconception is that changing the log level automatically changes the message structure. In reality, Mosquitto uses the log_type configuration option to select which categories of events are written to the log file or stdout. This setting accepts multiple values separated by commas. The most relevant types for connection monitoring are connection, disconnection, and error. If your logs are empty or missing connection events, verify your mosquitto.conf contains a line such as:
log_type connection
log_type disconnection
log_type error
Without explicitly enabling connection, the broker will not write the detailed handshake information required for parsing. You can also direct these logs to specific destinations using log_dest file /var/log/mosquitto/mosquitto.log or log_dest stdout. Understanding this distinction prevents the futile attempt to filter logs that were never generated in the first place due to incorrect type selection.

The Standard Connection Log Format

When a client successfully connects, Mosquitto generates a specific string pattern. Recognizing this pattern is crucial for accurate parsing. The default format when log_format standard is active looks like this:
New client connected from 192.168.1.50:54321 as ClientID123 (c0, k60).
Breaking down this structure reveals the data points available for extraction:
  • Prefix: The literal string "New client connected from".
  • Address: The IPv4 or IPv6 address followed by a colon and the ephemeral port number.
  • Client ID: The unique identifier assigned to the client session. This appears immediately after the word "as".
  • Flags: Enclosed in parentheses, c0 indicates clean session state, and k60 represents the keep-alive interval in seconds.
It is critical to note that if the client does not provide a Client ID during the CONNECT packet, Mosquitto assigns one internally but logs it as "anonymous". Therefore, any parser expecting a hexadecimal string or UUID in the client ID position will fail on unconfigured IoT devices. Always account for the possibility of the string "anonymous" appearing in the expected ID slot.

Parsing with Command Line Tools

For system administrators needing to monitor connections in real-time, command-line tools offer efficient solutions. While previous drafts suggested using awk with fixed field indices, the reliability depends on consistent spacing. The standard log format uses single spaces between fields, making awk a viable option if applied correctly. To extract just the Client ID from a stream of logs, you can use:
grep "New client connected" mosquitto.log | awk '{print $5}'
This command filters for connection events and prints the fifth whitespace-delimited field. In the example New client connected from 192.168.1.50:54321 as ClientID123..., the fields are:
  1. New
  2. client
  3. connected
  4. from
  5. 192.168.1.50:54321
  6. as
  7. ClientID123
Wait, the previous analysis shows that field 5 is the IP:Port, not the ID. The Client ID is actually the seventh field if we count strictly by space separation in the standard format. Let us re-evaluate.
New(1) client(2) connected(3) from(4) 192.168.1.50:54321(5) as(6) ClientID123(7)
Thus, the correct awk command to get the Client ID is:
grep "New client connected" mosquitto.log | awk '{print $7}'
If you need both the IP and the ID, you can capture them together:
grep "New client connected" mosquitto.log | awk '{print $5, $7}'
This approach assumes the standard log format. If you have switched to JSON logging via log_format json, this text-based parsing will fail entirely, requiring a different toolset.

Handling Edge Cases and Anonymous Clients

Parsing logic must be robust enough to handle non-standard client behaviors. As mentioned, anonymous clients are logged as "anonymous" instead of a unique ID. If your application relies on tracking specific device IDs, you might want to filter these out or flag them for security review. Additionally, consider the impact of IPv6 addresses. An IPv6 address like ::1 does not contain colons that might confuse simple parsers looking for the last colon as a separator between IP and Port. However, since the format always includes the port after a colon (e.g., [::1]:54321 for some implementations or just ::1:54321), relying on the positional index ($5 for IP, $7 for ID) remains safer than regex-based splitting on delimiters. For more complex environments where MQTT integration is challenging, see our guide on Solving Difficult MQTT Connection Issues in Node-RED on Raspberry Pi. This resource covers broader connectivity problems that may manifest as irregular log entries.

Alternative: JSON Logging for Structured Data

If you are building a scalable monitoring system, parsing plain text logs is fragile. Mosquitto supports JSON logging, which structures each event into a machine-readable object. Enable this by adding log_format json to your configuration. A JSON-formatted connection event looks like this:
{"timestamp":"2023-10-27T10:00:00Z","type":"connection","clientid":"ClientID123","ipaddress":"192.168.1.50","port":54321}
Using tools like jq, you can extract data without worrying about field positions:
cat mosquitto.log | jq -r 'select(.type=="connection") | .clientid'
This method is significantly more reliable for production environments. It handles special characters in client IDs gracefully and provides explicit keys for IP and port, eliminating ambiguity. For scripts that need to run with elevated privileges to access these logs securely, refer to Run Programs with Elevated Privileges: A Comprehensive Guide.

Frequently Asked Questions

Why are my connection logs missing?

Check your mosquitto.conf file to ensure log_type connection is explicitly enabled. By default, some configurations only enable errors, hiding normal connection activity.

How do I parse IPv6 addresses correctly?

Use positional field extraction (like awk '{print $5}') rather than splitting on colons. IPv6 addresses contain multiple colons, which breaks delimiter-based parsers.

What does "anonymous" mean in the logs?

It indicates the connecting client did not provide a Client ID in its CONNECT packet. Mosquitto assigns a temporary internal ID but logs it as "anonymous" for privacy and simplicity.

Can I use grep to find disconnected clients?

Yes, but you must also enable log_type disconnection in your config. The log message will start with "Client disconnected" instead of "New client connected".

Is JSON logging better than standard text logs?

JSON is superior for automated parsing and integration with monitoring systems. It avoids issues with variable spacing and special characters found in text-based formats.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More