Last active
January 19, 2020 13:04
-
-
Save mikhailov/d56df87a8146863f1725c2bae6f16d06 to your computer and use it in GitHub Desktop.
MySQL Process List redirect to STDOUT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -ex | |
# Inject APM Trace ID (part of SQL query comment) to a Log event | |
# https://docs.datadoghq.com/tracing/advanced/connect_logs_and_traces/?tab=ruby | |
# Input: {"command": "Query", "current_statement": "SELECT ... /* 4572859165692197980 */"} | |
# Output: {"process_list": {"current_statement": "SELECT ... /* 4572859165692197980 */"}, "dd": {"trace_id": 4572859165692197980}} | |
function inject_trace_id() { | |
trace_id=$(echo "$1" |grep -Eo '/\* [0-9]{16,20} \*/' | awk '{print $2}') | |
if [ -z "$trace_id" ] | |
then | |
echo "{\"process_list\": $1}" | |
else | |
echo "{\"process_list\": $1, \"dd\": {\"trace_id\": ${trace_id}}}" | |
fi | |
} | |
# Process List poll to JSON format, duration transform to millisecond unit | |
# Output multiline: {"command": "Query", "current_statement": "SELECT ... /* 4572859165692197980 */"} | |
function process_list() { | |
/usr/bin/mysql -h127.0.0.1 -uroot -p111111 -P6033 -s -r -e "SELECT | |
JSON_OBJECT( | |
'thd_id', thd_id, | |
'conn_id', conn_id, | |
'command', command, | |
'state', state, | |
'current_statement', current_statement, | |
'statement_latency', statement_latency / 1000, | |
'progress', progress, | |
'lock_latency', lock_latency / 1000, | |
'rows_examined', rows_examined, | |
'rows_sent', rows_sent, | |
'rows_affected', rows_affected, | |
'tmp_tables', tmp_tables, | |
'tmp_disk_tables', tmp_disk_tables, | |
'full_scan', full_scan, | |
'last_statement', last_statement, | |
'last_statement_latency', last_statement_latency / 1000 | |
) | |
FROM sys.x\$processlist | |
WHERE pid IS NOT NULL | |
AND db != 'sys';" | |
} | |
# Read process list output line by line and redirect to STDOUT twice a second, STDOUT -> Datadog Logs | |
while true; do | |
process_list | while read -r item; do | |
inject_trace_id "$item" > /proc/1/fd/1 | |
done | |
sleep 0.5; | |
done | |
# MIT License |
Author
mikhailov
commented
Oct 28, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment