epok
View as Markdown

MySQL and MariaDB

The OpenTelemetry Collector reads MySQL and MariaDB metrics with its MySQL and MariaDB receiver and tails the server log with the filelog receiver, then sends both to Epok over OTLP/HTTP. Run it on the database host or next to it. Tested with MySQL 8.4 over TLS (CA-verified) with these grants, MySQL 8.4 source and replica, and MariaDB 11.4 and collector 0.162.0.

1. Create a monitoring user

PROCESS and REPLICATION CLIENT read server status and replica status; SELECT on performance_schema only (table and index I/O waits). The user cannot read your tables or change data. The password goes in on stdin, not on the command line.

bash
read -rsp 'Monitoring password: ' P; echo
mysql -u root -p <<SQL
CREATE USER 'epok_monitor'@'%' IDENTIFIED BY '${P}';
GRANT PROCESS, REPLICATION CLIENT ON *.* TO 'epok_monitor'@'%';
GRANT SELECT ON performance_schema.* TO 'epok_monitor'@'%';
SQL
unset P

2. Turn on the logs you want

The config reads the error log and the slow query log. Slow entries are parsed into query_time_s, lock_time_s, rows_sent, rows_examined and the statement, and carry slow_query:true.

ini
[mysqld]
log_error           = /var/log/mysql/error.log
slow_query_log      = ON
slow_query_log_file = /var/log/mysql/slow.log
long_query_time     = 0.5
log_output          = FILE

The collector's user must be able to read the log files. On most installs that means adding it to the database's group. Change the include: paths if your logs live elsewhere.

Personal data: statement text can contain email addresses, names or tokens. On your host, before anything is sent, each slow-log statement goes through one left-to-right scan: every literal ('…' and "…" strings, X'…', B'…', N'…', _charset'…', numbers, hexadecimal and bit values) becomes ?, comments are dropped and IN (…) lists become IN (?). A string with a backslash, or an unclosed quote or comment, masks the whole rest of the statement, because where it ends depends on the server's sql_mode. A slow-log entry or an error-log line the parser cannot read is masked whole except its timestamp and marked redaction:unparsed_line_masked. If a redaction step fails, the collector drops the batch instead of sending it.

3. Run the collector

Install otel/opentelemetry-collector-contrib:0.162.0 (or the matching otelcol-contrib package). Put EPOK_INGEST_KEY (an ingest-only key from Settings, then API Keys) and MYSQL_MONITOR_PASSWORDin the collector's environment file, mode 0600, typed at a prompt that does not echo. Neither goes in the config file or on a command line.

bash
read -rsp 'Epok ingest key: ' K; echo; read -rsp 'Monitoring password: ' P; echo
printf 'EPOK_INGEST_KEY=%s\nMYSQL_MONITOR_PASSWORD=%s\n' "$K" "$P" | sudo tee -a /etc/otelcol-contrib/otelcol-contrib.conf >/dev/null
unset K P
sudo chmod 600 /etc/otelcol-contrib/otelcol-contrib.conf

The connection is TLS with the server certificate verified: set endpoint to the server name in its certificate and ca_file to the CA that signed it. Plain TCP is only for a collector on the database host; the file shows those localhost lines as a comment. The same file is in the app under Connect.

yaml
# otelcol-mysql.yaml: MySQL / MariaDB metrics + error log + slow query log to Epok
# Collector: otel/opentelemetry-collector-contrib:0.162.0 (pinned; tested with MySQL 8.4 and MariaDB 11.4)
#
# Secrets never go in this file or on a command line. Put them in the collector's
# environment file (otelcol-contrib package: /etc/otelcol-contrib/otelcol-contrib.conf,
# or an EnvironmentFile= of your own, mode 0600):
#   read -rsp 'Epok ingest key: ' K; echo; read -rsp 'Monitoring password: ' P; echo
#   printf 'EPOK_INGEST_KEY=%s\nMYSQL_MONITOR_PASSWORD=%s\n' "$K" "$P" | sudo tee -a /etc/otelcol-contrib/otelcol-contrib.conf >/dev/null
#   unset K P
#
# Monitoring user: server status and replica status, plus performance_schema only (no
# access to your tables). The password goes in on stdin, not on argv:
#   read -rsp 'Monitoring password: ' P; echo
#   mysql -u root -p <<SQL
#   CREATE USER 'epok_monitor'@'%' IDENTIFIED BY '${P}';
#   GRANT PROCESS, REPLICATION CLIENT ON *.* TO 'epok_monitor'@'%';
#   GRANT SELECT ON performance_schema.* TO 'epok_monitor'@'%';
#   SQL
#   unset P

receivers:
  mysql:
    endpoint: db.example.internal:3306   # the server's name as it appears in its TLS certificate
    username: epok_monitor
    password: ${env:MYSQL_MONITOR_PASSWORD}
    collection_interval: 30s
    tls:
      insecure: false            # TLS on and the server certificate verified
      ca_file: /etc/otelcol-contrib/db-ca.pem   # the CA that signed the server certificate
      # LOCALHOST ONLY (collector on the database host, server without TLS):
      #   endpoint: localhost:3306
      #   tls: {insecure: true}
    metrics:
      mysql.connection.count: {enabled: true}
      mysql.connection.errors: {enabled: true}
      mysql.max_used_connections: {enabled: true}
      mysql.query.count: {enabled: true}
      mysql.query.slow.count: {enabled: true}
      mysql.replica.time_behind_source: {enabled: true}
      mysql.replica.sql_delay: {enabled: true}

  # Error log (log_error) and slow query log (slow_query_log = ON,
  # long_query_time = 0.5, log_output = FILE).
  filelog/mysql_error:
    include: [/var/log/mysql/error.log]
    start_at: end
    operators:
      # MySQL 8: 2026-11-20T10:00:00.123456Z 0 [Warning] [MY-010068] [Server] message
      # MariaDB: 2026-11-20 10:00:00 0 [Warning] message
      - type: regex_parser
        regex: '^(?P<mysql_time>\S+(?: \d{2}:\d{2}:\d{2})?) +(?P<mysql_thread>\d+) \[(?P<mysql_level>\w+)\] (?:\[(?P<mysql_error_code>MY-\d+)\] \[(?P<mysql_subsystem>\w+)\] )?(?P<message>.*)$'
        on_error: send
        severity:
          parse_from: attributes.mysql_level
          mapping:
            error: [ERROR, Error]
            warn: [Warning, Warn]
            info: [System, Note, Info]
      - type: move
        if: 'attributes.message != nil'
        from: attributes.message
        to: body
      - type: add
        field: attributes.db_system
        value: mysql
  filelog/mysql_slow:
    include: [/var/log/mysql/slow.log]
    start_at: end
    multiline:
      line_start_pattern: '^# Time: '
    operators:
      - type: regex_parser
        regex: '(?s)^# Time: (?P<mysql_time>\S+)\n# User@Host: (?P<db_user>[^\[\s]*)\[[^\]]*\] @ +(?P<client_host>\S*) *\[(?P<client_ip>[^\]]*)\].*?\n# Query_time: (?P<query_time_s>[0-9.]+) +Lock_time: (?P<lock_time_s>[0-9.]+) +Rows_sent: (?P<rows_sent>\d+) +Rows_examined: (?P<rows_examined>\d+).*?\n(?:use (?P<db_name>[^;]+);\n)?(?:SET timestamp=\d+;\n)?(?P<statement>.*?)\s*$'
        on_error: send
      - type: add
        field: attributes.slow_query
        value: "true"
      - type: add
        field: attributes.db_system
        value: mysql
      - type: severity_parser
        parse_from: attributes.slow_query
        mapping:
          warn: "true"
      - type: copy
        if: 'attributes.statement != nil'
        from: attributes.statement
        to: body

processors:
  batch:
    send_batch_max_size: 10000   # at or under Epok's 10,000 entries per batch
  resourcedetection:
    detectors: [env, system]
    system:
      hostname_sources: [os]
  resource/mysql:
    attributes:
      - key: service.name
        value: mysql
        action: upsert
  # Statement text can carry personal data. The slow-log statement is read by ONE left-to-right
  # scan: every literal ('…', "…", X'…'/B'…'/N'…'/_charset'…', $$…$$, numbers, 0x…, 0b…)
  # becomes ?, comments (/* */, --, #) are dropped, `identifiers` and keywords stay, and IN (…)
  # lists collapse to IN (?). A string with a backslash (its end depends on sql_mode), an
  # unclosed quote or comment masks the WHOLE rest of the statement. A slow-log entry or an
  # error-log line the parser cannot read is masked whole (redaction=unparsed_line_masked).
  # Error-log lines: the text from the
  # first to the last quote, e-mail addresses, 0x…/0b…, numbers of 3+ digits, Failing row
  # contains (…) tuples and Key (…)=(…) values become ?.
  transform/redact_sql:
    error_mode: propagate     # a redaction step that fails drops the batch; nothing is sent unredacted
    log_statements:
      - context: log
        conditions:
          - attributes["slow_query"] == "true" and attributes["statement"] != nil
        statements:
          - 'replace_pattern(attributes["statement"], "(`(?:[^`]|``)*`)|(?i:\\b(?:[xbn]|_[a-z0-9]+))?('')(?:[^''\\\\]|'''')*''|(?i:\\b(?:[xbn]|_[a-z0-9]+))?('')(?:[^''\\\\]|'''')*\\\\(?s:.*)|(\")(?:[^\"\\\\]|\"\")*\"|(\")(?:[^\"\\\\]|\"\")*\\\\(?s:.*)|(\\$$\\$$)(?s:.*?)\\$$\\$$|(\\$$\\$$)(?s:.*)|/\\*(?s:.*?)\\*/|(/\\*)(?s:.*)|--[^\\n]*|#[^\\n]*|('')(?s:.*)|(\")(?s:.*)|`(?s:.*)|([A-Za-z0-9_$$]+)", "$${1}$${2}$${3}$${4}$${5}$${6}$${7}$${8}$${9}$${10}$${11}")'
          - 'replace_pattern(attributes["statement"], "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", "?")'
          - 'replace_pattern(attributes["statement"], "[''\"]|\\$$\\$$|/\\*", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\b0x[0-9a-f_]+\\b", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\b0b[01]+\\b", "?")'
          - 'replace_pattern(attributes["statement"], "\\b\\d[\\d_]*(?:\\.[\\d_]*)?(?:[eE][+-]?\\d+)?\\b", "?")'
          - 'replace_pattern(attributes["statement"], "(?i)\\bIN\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)", "IN (?)")'
          - set(body, attributes["statement"])
      - context: log
        conditions:
          - attributes["slow_query"] == "true" and attributes["statement"] == nil
        statements:
          - 'replace_pattern(body, "^(\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?(?: [A-Z]{2,5})? )?(?s:.*)$$", "$${1}?")'
          - set(attributes["redaction"], "unparsed_line_masked")
      - context: log
        conditions:
          - attributes["slow_query"] != "true"
        statements:
          - 'replace_pattern(body, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", "?")'
          - 'replace_pattern(body, "Failing row contains \\((?s:.*)\\)", "Failing row contains (?)")'
          - 'replace_pattern(body, "\\)=\\((?s:.*)\\)", ")=(?)")'
          - 'replace_pattern(body, "[''\"](?s:.*)[''\"]", "?")'
          - 'replace_pattern(body, "[''\"](?s:.*)", "?")'
          - 'replace_pattern(body, "(?i)\\b0x[0-9a-f]+\\b", "?")'
          - 'replace_pattern(body, "(?i)\\b0b[01]+\\b", "?")'
          - 'replace_pattern(body, "\\b\\d{3,}(?:\\.\\d+)?\\b", "?")'
      - context: log
        conditions:
          - attributes["slow_query"] != "true" and attributes["mysql_level"] == nil
        statements:
          - 'replace_pattern(body, "^(\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?(?: [A-Z]{2,5})? )?(?s:.*)$$", "$${1}?")'
          - set(attributes["redaction"], "unparsed_line_masked")

exporters:
  otlphttp/epok:
    metrics_endpoint: https://ingest.epok.cloud/v1/metrics
    logs_endpoint: https://ingest.epok.cloud/v1/logs
    compression: gzip
    encoding: json
    headers:
      x-api-key: ${env:EPOK_INGEST_KEY}

service:
  pipelines:
    metrics:
      receivers: [mysql]
      processors: [resourcedetection, resource/mysql, batch]
      exporters: [otlphttp/epok]
    logs:
      receivers: [filelog/mysql_error, filelog/mysql_slow]
      processors: [resourcedetection, resource/mysql, transform/redact_sql, batch]
      exporters: [otlphttp/epok]

4. Check that data arrives

Metrics arrive within a minute (one point every 30 seconds). In Metrics, search for any of these names:

mysql_threads, mysql_query_count, mysql_query_slow_count, mysql_buffer_pool_operations, mysql_buffer_pool_usage, mysql_replica_time_behind_source, mysql_row_locks, mysql_connection_errors

Logs are searchable in Explore with these queries:

  • service:mysql -record_type:metric slow_query:true: slow query log entries with timings and the statement
  • service:mysql -record_type:metric -slow_query:true level:(error OR warn): error log errors and warnings
  • service:mysql -record_type:metric: every log line (-record_type:metric leaves out the metric points, which are also stored with service:mysql)

Dashboard

When database boards are on for your workspace, Settings, then Setup, then Quickstarts installs the MySQL and MariaDB board: connections, throughput, latency or slow queries, cache hit ratio, replication and errors. Without it, every metric and log above is searchable and can be charted on your own dashboards.

Limits

  • A string that contains a backslash (such as 'C:\temp' or 'O\'Brien') masks the rest of its statement, because where it ends depends on sql_mode.
  • Replica lag is reported by each replica. Run the collector on every replica as well as the source.
  • Slow query entries keep table and column names, and send the entry header's user, host and client IP as db_user, client_host and client_ip.
  • Error-log lines get the safer default only: everything from the first to the last quote, email addresses, hexadecimal values and numbers of 3 or more digits become ?. Other text in them is sent as written.
  • No query samples, normalized query statistics or explain plans. Epok reads server metrics and logs only.

OpenTelemetry CollectorAll install guides