'How to log queries to stdout on MySQL?

MySQL 5.6.26

Trying to log queries to stdout doesn't work below,

$ mysqld --general_log=1 --general_log_file=/dev/stdout


Solution 1:[1]

I am very surprised at how difficult it is to do this in MySQL vs. PostgreSQL.

Following below is the config that allowed me to send all MySQL logs to the Docker container's stdout.

Contents of docker-compose.yml:

---
version: "3.9"
services:
  your_db:
    image: mysql:5.7-debian
    command:
      - /usr/local/bin/mysqld.sh
    environment:
      MYSQL_DATABASE: "$your_db"
      MYSQL_PASSWORD: "$your_pass"
      MYSQL_ROOT_PASSWORD: "$root_pass"
      MYSQL_USER: "$your_user"
    volumes:
      - ./my.cnf:/etc/mysql/conf.d/my.cnf:ro
      - ./mysqld.sh:/usr/local/bin/mysqld.sh:ro
    networks:
      - your_net

Contents of my.cnf:

[mysqld]
# Log General
general_log = 1
general_log_file = /var/log/mysql_general.log

# Log Error
log_error = /var/log/mysql_error.log

# Log Slow
slow_query_log = 1
slow_query_log_file = /var/log/mysql_slow_query.log
long_query_time = 0  # 0 has the effect of logging all queries
log_queries_not_using_indexes = 1

Contents of mysqld.sh:

#!/usr/bin/env bash
set -euo pipefail

##
# This script exists to work-around the fact that
# mysql does not support logging to stdout
#
# This will tail the file logs configured in ./my.cnf
##

LOG_PATHS=(
  '/var/log/mysql_general.log'
  '/var/log/mysql_error.log'
  '/var/log/mysql_slow_query.log'
)
for LOG_PATH in "${LOG_PATHS[@]}"; do
  # https://serverfault.com/a/599209
  ( umask 0 && truncate -s0 "$LOG_PATH" )
  tail --pid $$ -n0 -F "$LOG_PATH" &
done

docker-entrypoint.sh mysqld

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1