All pages
Powered by GitBook
1 of 24

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Binary Log

Understand the binary log in MariaDB Server. This section explains its role in replication and point-in-time recovery, detailing its format, management, and use for data integrity.

Server Monitoring & Logs

Learn about MariaDB Server monitoring and logs. This section guides you through using various logs & monitoring tools to track database activity, troubleshoot issues, and ensure optimal performance.

Overview of the Binary Log

Introduction to the purpose and structure of the binary log, explaining how it records data changes (DML) and structure changes (DDL) for replication and recovery.

The binary log contains a record of all changes to the databases, both data and structure, as well as how long each statement took to execute. It consists of a set of binary log files and an index.

This means that statements such as CREATE, ALTER, INSERT, UPDATE and DELETE will be logged, but statements that have no effect on the data, such as SELECT and SHOW, will not be logged. If you want to log these (at a cost in performance), use the general query log.

If a statement may potentially have an effect, but doesn't, such as an UPDATE or DELETE that returns no rows, it will still be logged (this applies to the default statement-based logging, not to row-based logging - see Binary Log Formats).

The purpose of the binary log is to allow replication, where data is sent from one or more masters to one or more slave servers based on the contents of the binary log, as well as assisting in backup operations.

A MariaDB server with the binary log enabled will run slightly more slowly.

It is important to protect the binary log, as it may contain sensitive information, including passwords.

Binary logs are stored in a binary, not plain text, format, and so are not viewable with a regular editor. However, MariaDB includes , a commandline tool for plain text processing of binary logs.

This page is licensed: CC BY-SA / Gnu FDL

mariadb-binlog

Transaction Coordinator Log

Explains the Transaction Coordinator Log (tc.log), used to maintain consistency in distributed transactions (XA) across multiple storage engines or servers.

Relay Log

Overview of the relay log, a set of log files created by a replica server to store events received from the primary's binary log before executing them.

The relay log is a set of log files created by a replica during replication.

It's the same format as the binary log, containing a record of events that affect the data or structure; thus, mariadb-binlog can be used to display its contents. It consists of a set of relay log files and an index file containing a list of all relay log files.

Events are read from the primary's binary log and written to the replica's relay log. They are then performed on the replica. Old relay log files are automatically removed once they are no longer needed.

Creating Relay Log Files

New relay log files are created by the replica at the following times:

  • When the IO thread starts.

  • When the logs are flushed, with or .

  • When the maximum size, determined by the system variable, has been reached.

Relay Log Names

By default, the relay log will be given a name host_name-relay-bin.nnnnnn, with host_name referring to the server's host name, and #nnnnnnthe sequence number.

This causes problems if the replica's host name changes, returning this error:

To prevent this, you can specify the relay log file name by setting the and system variables.

If you need to overcome this issue while replication is already underway,you can stop the replica, prepend the old relay log index file to the new relay log index file, and restart the replica.

For example:

Viewing Relay Logs

The shows events in the relay log, and, since relay log files are the same format as binary log files, they can be read with the utility.

Removing Old Relay Logs

Old relay logs are automatically removed once all events have been implemented on the replica, and the relay log file is no longer needed. This behavior can be changed by adjusting the system variable from its default of 1 to 0, in which case the relay logs will be left on the server.

Relay logs are also removed by the statement unless a is used.

One can also flush the logs with the commands.

If the relay logs are taking up too much space on the replica, the system variable can be set to limit the size. The IO thread will stop until the SQL thread has cleared the backlog. By default there is no limit.

See also

This page is licensed: CC BY-SA / Gnu FDL

Overview of MariaDB Logs

An introductory guide to the various logs available in MariaDB, including the Error Log, General Query Log, Slow Query Log, and Binary Log, and how to enable or disable them.

There are many variables in MariaDB that you can use to define what to log and when to log.

This article will give you an overview of the different logs and how to enable/disable logging to these.

Note that storage engines can have their logs too: for example, InnoDB keeps an and a Redo Log which are used for rollback and crash recovery. However, this page only lists MariaDB server logs.

MyISAM Log

Explains the MyISAM log (`myisam.log`), a specialized log for recording changes to MyISAM tables for debugging purposes, enabled via the `--log-isam` option.

The MyISAM log records all changes to tables. It is not enabled by default. To enable it, start the server with the option, for example:

The isam instead of myisam above is not a typo - it's a legacy from when the predecessor to the MyISAM format, called ISAM. The option can be used without specifying a filename, in which case the default, myisam.log is used.

To process the contents of the log file, use the utility.

This page is licensed: CC BY-SA / Gnu FDL

Slow Query Log

Utilize the slow query log in MariaDB Server. This section helps you identify and optimize inefficient queries, improving overall database performance and responsiveness.

Always enabled

  • Usually a file in the data directory, but some distributions may move this to other locations.

  • All critical errors are logged here.

  • One can get warnings to be logged by setting log_warnings.

  • With the mysqld_safe --syslog option one can duplicate the messages to the system's syslog.

  • General Query Log

    • Enabled with --general-log

    • Logs all queries to a file or table.

    • Useful for debugging or auditing queries.

    • The super user can disable logging to it for a connection by setting SQL_LOG_OFF to 1.

    Slow Query Log

    • Enabled by starting mysqld with --slow-query-log

    • Logs all queries to a file or table.

    • Useful to find queries that causes performance problems.

    • Logs all queries that takes more than long_query_time to run.

    • One can decide what to log with the options , , or .

    • One can change what is logged by setting .

    • One can disable it globally by setting to 0

    • In 10.1 one can disable it for a connection by setting to 0.

    Binary Log

    • Enabled by starting mysqld with --log-bin

    • Used on machines that are, or may become, replication masters.

    • Required for point-in-time recovery.

    • Binary log files are mainly used by replication and can also be used with mariadb-binlog to apply on a backup to get the database up to date.

    • One can decide what to log with or .

    • The super user can disable logging for a connection by to 0. However while this is 0, no changes done in this connection will be replicated to the slaves!

    • For examples, see .

    Examples

    If you know that your next query will be slow and you don't want to log it in the slow query log, do:

    If you are a super user running a log batch job that you don't want to have logged (for example mariadb-dump), do:

    mariadb-dump (previously mysqldump) since will add this automatically to your dump file if you run it with the --skip-log-queries option.

    See Also

    • MariaDB audit plugin

    This page is licensed: CC BY-SA / Gnu FDL

    Undo Log
    Error Log
    FLUSH LOGS
    mariadb-admin flush-logs
    max_relay_log_size
    relay_log
    relay_log_index
    SHOW RELAYLOG EVENTS
    mariadb-binlog
    relay_log_purge
    CHANGE MASTER
    relay log option
    FLUSH RELAY LOGS
    relay_log_space_limit
    FLUSH RELAY LOGS
    --log-isam=myisam.log
    MyISAM
    --log-isam
    myisamlog

    Compressing Events to Reduce Size of the Binary Log

    Guide to using the `log_bin_compress` system variable to compress binary log events, reducing storage usage and network bandwidth during replication.

    Selected events in the binary log can be optionally compressed, to save space in the binary log on disk and in network transfers.

    The events that can be compressed are the events that normally can be of a significant size: Query events (for DDL and DML in statement-based replication), and row events (for DML in row-based replication).

    Compression is fully transparent. Events are compressed on the primary before being written into the binary log, and are uncompressed by the I/O thread on the replica before being written into the relay log. The mariadb-binlog command will likewise uncompress events for its output.

    Currently, the zlib compression algorithm is used to compress events.

    Compression will have the most impact when events are of a non-negligible size, as each event is compressed individually. For example, batch INSERT statements that insert many rows or large values, or row-based events that touch a number of rows in one query.

    The log_bin_compress option is used to enable compression of events. Only events with data (query text or row data) above a certain size are compressed; the limit is set with the log_bin_compress_min_len option.

    This page is licensed: CC BY-SA / Gnu FDL

    log_slow_always_query_time System Variable

    Documentation for the `log_slow_always_query_time` variable, which forces queries executed by a specific function or user to be logged regardless of their execution time.

    • Description: Queries slower than log_slow_always_query_time are not affected by or . Query will be logged to the if the execution time of the query is longer than and log_slow_always_query_time. The argument will be treated as a decimal value with microsecond precision.

    • Command line: --log-slow-always-query-time=num

    EXPLAIN in the Slow Query Log

    Describes how to configure MariaDB to automatically write the `EXPLAIN` plan for slow queries to the log using the `log_slow_verbosity` system variable.

    Switching it On

    output can be switched on by specifying the explain keyword in the system variable. Alternatively, you can set with the log-slow-verbosity command line argument.

    EXPLAIN output will only be recorded if the slow query log is written to a file (and not to a table - see ). This limitation also applies to other extended statistics that are written into the slow query log.

    SET LOCAL SLOW_QUERY_LOG=0;
    SET LOCAL SQL_LOG_OFF=1, LOCAL SLOW_QUERY_LOG=0;
    Failed to open the relay log and Could not find target log during relay log initialization
    shell> cat NEW_relay_log_name.index >> OLD_relay_log_name.index
    shell> mv OLD_relay_log_name.index NEW_relay_log_name.index
    What it Looks Like

    When explain recording is on, slow query log entries look like this:

    EXPLAIN lines start with explain:.

    See Also

    • MDEV-407

    This page is licensed: CC BY-SA / Gnu FDL

    EXPLAIN
    log_slow_verbosity
    Writing logs into tables
    [mysqld]
    log-slow-verbosity=query_plan,explain
    # Time: 131112 17:03:32
    # User@Host: root[root] @ localhost []
    # Thread_id: 2  Schema: dbt3sf1  QC_hit: No
    # Query_time: 5.524103  Lock_time: 0.000337  Rows_sent: 1  Rows_examined: 65633
    #
    # explain: id   select_type     table   type    possible_keys   key     key_len ref     rows    Extra
    # explain: 1    SIMPLE  nation  ref     PRIMARY,n_name  n_name  26      const   1       Using where; Using index
    # explain: 1    SIMPLE  customer        ref     PRIMARY,i_c_nationkey   i_c_nationkey   5       dbt3sf1.nation.n_nationkey      3145    Using index
    # explain: 1    SIMPLE  orders  ref     i_o_custkey     i_o_custkey     5       dbt3sf1.customer.c_custkey      7       Using index
    #
    SET TIMESTAMP=1384261412;
    SELECT COUNT(*) FROM customer, orders, nation WHERE c_custkey=o_custkey AND c_nationkey=n_nationkey AND n_name='GERMANY';
    Scope: Global, Session
  • Dynamic: Yes

  • Data Type: numeric (double)

  • Default Value: 31536000.000000

  • Range: 0 to 31536000

  • Introduced:

  • This page is licensed: CC BY-SA / Gnu FDL

    log_slow_rate_limit
    log_slow_min_examined_row_limit
    slow query log
    log_slow_query_time
    --log-slow-admin-statements
    --log-slow-slave-statements
    log_slow_filter
    log_slow_rate_limit
    log_slow_verbosity
    global.slow_query_log
    local.slow_query_log
    --binlog-ignore-db=database_name
    --binlog-do-db=database_name
    setting SQL_LOG_BIN
    Using and Maintaining the Binary Log

    Flashback

    Explains how to use the Flashback feature (via `mysqlbinlog --flashback`) to rollback transactions by reversing the binary log events, useful for recovering from accidental data modifications.

    Flashback is a feature that allows instances, databases or tables to be rolled back to an old snapshot.

    Flashback is currently supported only over DML statements (INSERT, DELETE, UPDATE). An upcoming version of MariaDB will add support for flashback over DDL statements (DROP, TRUNCATE, ALTER, etc.) by copying or moving the current table to a reserved and hidden database, and then copying or moving back when using flashback. See MDEV-10571.

    Flashback is achieved in MariaDB Server using existing support for full image format binary logs (binlog_row_image=FULL), so it supports all engines.

    The real work of Flashback is done by mariadb-binlog with --flashback. This causes events to be translated: INSERT to DELETE, DELETE to INSERT, and for UPDATE statements, the before and after images are swapped.

    When executing mariadb-binlog with --flashback, the Flashback events are stored in memory. You must make sure your server has enough memory for this feature.

    Arguments

    • has the option --flashback or -B that lets it work in flashback mode.

    • has the option that enables the binary log and sets binlog_format=ROW. It is not mandatory to use this option if you have already enabled those options directly.

    Do not use -v -vv options, as this adds verbose information to the binary log which can cause problems when importing. See and .

    Example

    With a table "mytable" in database "test", you can compare the output with --flashback and without.

    If you know the exact position, --start-position can be used instead of --start-datetime.

    Then, by importing the output file (mariadb < flashback.sql), you can flash your database/table back to the specified time or position.

    Common Use Case

    A common use case for Flashback is the following scenario:

    • You have one primary and two replicas, one started with --flashback (i.e. with binary logging enabled, using , and ).

    • Something goes wrong on the primary (like a wrong update or delete) and you would like to revert to a state of the database (or just a table) at a certain point in time.

    • Remove the flashback-enabled replica from replication.

    This page is licensed: CC BY-SA / Gnu FDL

    Activating the Binary Log

    Instructions for enabling the binary log using the `--log-bin` option and configuring the log file basename and index file.

    To enable binary logging, start the server with the [--log-bin [=name](../../../server-usage/replication-cluster-multi-master/standard-replication/replication-and-binary-log-system-variables.md)] option.

    If you specify a filename with an extension (for example .log), the extension will be silently ignored.

    If you don't provide a name (which can, optionally, include an absolute path), the default is datadir/log-basename-bin, datadir/mysql-bin or datadir/mariadb-bin (the latter two if --log-basename is not specified, and dependent on server version). Datadir is determined by the value of the datadir system variable.

    We strongly recommend you use either or specify a filename to ensure that doesn't stop if the hostname of the computer changes.

    The directory storing the binary logs contains a binary log index, as well as the individual binary log files.

    The binary log files have a series of numbers as filename extensions. Each additional binary log increments the extension number, so the oldest binary logs have lower numbers, and the most recent ones have higher numbers.

    A new binary log, with a new extension, is created every time the server starts, the logs are flushed, or the maximum size is reached (determined by ).

    The binary log index file contains a master list of all the binary logs, in order. From , if is enabled (the default), an additional index file (.idx) is present.

    A sample listing from a directory containing the binary logs:

    The binary log index file has, by default, the same name as the individual binary logs, with the extension .index. You can specify an alternative name with the --log-bin-index [=filename] .

    Clients with the privilege (or, from , the privilege, can disable and re-enable the binary log for the current session by setting the variable.

    Binary Log Format

    There are three formats for the binary log. The default is , which is a mix of and . See for a full discussion.

    See Also

    • - Delete logs

    • - Close and rotate logs

    This page is licensed: CC BY-SA / Gnu FDL

    Heuristic Recovery with the Transaction Coordinator Log

    Describes the process of heuristic recovery using the TC log to resolve "in-doubt" transactions that may occur after a server crash during a 2-phase commit.

    The transaction coordinator log (tc_log) is used to coordinate transactions that affect multiple . One of the main purposes of this log is in crash recovery.

    Modes of Crash Recovery

    There are two modes of crash recovery:

    • Automatic crash recovery.

    Writing Logs Into Tables

    Instructions on directing the General Query Log and Slow Query Log to tables (`mysql.general_log`, `mysql.slow_log`) instead of files using the `log_output=TABLE` system variable.

    By default, all logs are disabled or written into files. The and the can also be written to special tables in the mysql database. During the startup, entries will always be written into files.

    Note that will only be recorded if the slow query log is written to a file and not to a table.

    To write logs into tables, the server system variable is used. Allowed values are FILE, TABLE and NONE. It is possible to specify multiple values, separated with commas, to write the logs into both tables and files. NONE disables logging and has precedence over the other values.

    So, to write logs into tables, one of the following settings can be used:

    Invoke
    to find the exact log position of the first offending operation after the state you want to revert to.
  • Run mariadb-binlog --flashback --start-position=xyz | mariadb to pipe the output of mariadb-binlog directly to the mariadb client, or save the output to a file and then direct the file to the command-line client.

  • mariadb-binlog
    mariadbd
    --flashback
    MDEV-12066
    MDEV-12067
    binlog_format=ROW
    binlog_row_image=FULL
    mariadb-binlog

    Manual heuristic recovery when --tc-heuristic-recover is set to some value other than OFF.

    Automatic Crash Recovery

    Automatic crash recovery occurs during startup when MariaDB needs to recover from a crash and --tc-heuristic-recover is set to OFF, which is the default value.

    Automatic Crash Recovery with the Binary Log-Based Transaction Coordinator Log

    If MariaDB needs to perform automatic crash recovery and if the binary log is enabled, then the error log will contain messages like this:

    Automatic Crash Recovery with the Memory-Mapped File-Based Transaction Coordinator Log

    If MariaDB needs to perform automatic crash recovery and if the binary log is not enabled, then the error log will contain messages like this:

    Manual Heuristic Recovery

    Manual heuristic recovery occurs when --tc-heuristic-recover is set to some value other than OFF. This might be needed if the server finds prepared transactions during crash recovery that are not in the transaction coordinator log. For example, the error log might contain an error like this:

    When manual heuristic recovery is initiated, MariaDB will ignore information about transactions in the transaction coordinator log during the recovery process. Prepared transactions that are encountered during the recovery process will either be rolled back or committed, depending on the value of --tc-heuristic-recover.

    When manual heuristic recovery is initiated, the error log will contain a message like this:

    Manual Heuristic Recovery with the Binary Log-Based Transaction Coordinator Log

    If --tc-heuristic-recover is set to some value other than OFF and if the binary log is enabled, then MariaDB will ignore information about transactions in the binary log during the recovery process. Prepared transactions that are encountered during the recovery process will either be rolled back or committed, depending on the value of --tc-heuristic-recover.

    After the recovery process is complete, MariaDB will create a new empty binary log file, so that the old corrupt ones can be ignored.

    Manual Heuristic Recovery with the Memory-Mapped File-Based Transaction Coordinator Log

    If --tc-heuristic-recover is set to some value other than OFF and if the binary log is not enabled, then MariaDB will ignore information about transactions in the memory-mapped file defined by the --log-tc option during the recovery process. Prepared transactions that are encountered during the recovery process will either be rolled back or committed, depending on the value of --tc-heuristic-recover.

    This page is licensed: CC BY-SA / Gnu FDL

    XA-capable
    storage engines
    The general log will be written into the general_log table, and the slow query log will be written into the slow_log table. Only a limited set of operations are supported for those special tables. For example, direct DML statements (like INSERT) on those tables will fail with an error similar to the following:

    To flush data to the tables, use FLUSH TABLES instead of FLUSH LOGS.

    To empty the contents of the log tables, TRUNCATE TABLE can be used.

    The log tables use the CSV storage engine by default. This allows an external program to read the files if needed: normal CSV files are stored in the mysql subdirectory, in the data dir. However that engine is slow because it does not support indexes, so you can convert the tables to MyISAM (but not other storage engines). To do so, first temporarily disable logging:

    CHECK TABLE and CHECKSUM TABLE are supported.

    CREATE TABLE is supported. ALTER TABLE, RENAME TABLE and DROP TABLE are supported when logging is disabled, but log tables cannot be partitioned.

    Contents of log tables are not logged in the binary log, thus cannot be replicated.

    This page is licensed: CC BY-SA / Gnu FDL

    general query log
    slow query log
    EXPLAIN output
    log_output
    mariadb-binlog /var/lib/mysql/mysql-bin.000001 -vv -d test -T mytable \
        --start-datetime="2013-03-27 14:54:00" > review.sql
    mariadb-binlog /var/lib/mysql/mysql-bin.000001 -vv -d test -T mytable \
        --start-datetime="2013-03-27 14:54:00" --flashback > flashback.sql
    [Note] Recovering after a crash using cmdb-mariadb-0-bin
    [Note] InnoDB: Buffer pool(s) load completed at 190313 11:24:29
    [Note] Starting crash recovery...
    [Note] Crash recovery finished.
    [Note] Recovering after a crash using tc.log
    [Note] InnoDB: Buffer pool(s) load completed at 190313 11:26:32
    [Note] Starting crash recovery...
    [Note] Crash recovery finished.
    [ERROR] Found 1 prepared transactions! It means that mysqld was not shut down properly last time and critical recovery information (last binlog or tc.log file) was manually deleted after a crash. You have to start mysqld with --tc-heuristic-recover switch to commit or rollback pending transactions.
    [Note] Heuristic crash recovery mode
    SET GLOBAL log_output = 'TABLE';
    SET GLOBAL log_output = 'FILE,TABLE';
    ERROR 1556 (HY000): You can't use locks with log tables.
    SET GLOBAL general_log = 'OFF';
    ALTER TABLE mysql.general_log ENGINE = MyISAM;
    ALTER TABLE mysql.slow_log ENGINE = MyISAM;
    SET GLOBAL general_log = @old_log_state;
    --log-basename
    replication
    max_binlog_size
    MariaDB 11.4
    GTID binlog indexing
    option
    SUPER
    BINLOG ADMIN
    sql_log_bin
    mixed logging
    statement-based
    row-based logging
    Binary Log Formats
    Setting sql_log_bin
    PURGE LOGS
    FLUSH LOGS
    GTID binlog indexing

    Binary Log Formats

    Detailed comparison of the three binary logging formats: Statement-based (SBR), Row-based (RBR), and Mixed, including their pros, cons, and configuration via `binlog_format`.

    Supported Binary Log Formats

    There are three supported formats for binary log events:

    • Statement-Based Logging

    • Row-Based Logging

    • Mixed Logging

    Regardless of the format, events are always stored in a binary format, rather than in plain text. MariaDB includes the utility that can be used to output events in a human-readable format.

    You may want to set the binary log format in the following cases:

    • If you execute single statements that update many rows, then statement-based logging will be more efficient than row-based logging for the replica to download.

    • If you execute many statements that don't affect any rows, then row-based logging will be more efficient than statement-based logging for the replica to download.

    • If you execute statements that take a long time to complete, but they ultimately only insert, update, or delete a few rows in the table, then row-based logging will be more efficient than statement-based logging for the replica to apply.

    The default is which is replication-safe and requires less storage space than .

    The storage engine API also allows storage engines to set or limit the logging format, which helps reduce errors with replicating between primaries and replicas with different storage engines.

    Statement-Based Logging

    When statement-based logging is enabled, statements are logged to the exactly as they were executed. Temporary tables created on the primary will also be created on the replica. This mode is only recommended where one needs to keep the binary log as small as possible, the primary and replica have identical data (including using the same storage engines for all tables), and all functions being used are deterministic (repeatable with the same arguments). Statements and tables using timestamps or auto_increment are safe to use with statement-based logging.

    This mode can be enabled by setting the system variable to STATEMENT.

    In certain cases when it would be impossible to execute the statement on the replica, the server will switch to row-based logging for the statement. Some cases of this are:

    • When replication has been changed from row-based to statement-based and a statement uses data from a temporary table created during row-based mode. In this case, the temporary tables are not stored on the replica, so row logging is the only alternative.

    • of a table using a storage engine that stores data remotely, such as the , to another storage engine.

    • One is using in the statement or the definition.

    In certain cases, a statement may not be deterministic, and therefore not safe for . If MariaDB determines that an unsafe statement has been executed, then it will issue a warning. For example:

    See for more information.

    If you need to execute non-deterministic statements, then it is safer to use mixed logging or row-based.

    Things to be aware of with statement-based logging

    Note that some tables, like temporary tables created in row mode, does not support statement based logging (as the data is not in the binary log). Any statement that uses a table that does not support statement logging will use row based logging. This is to ensure that the data on master and the slave are consistent.

    Statement-based logging was the default prior to and before. is now the default.

    Mixed Logging

    Mixed logging is the default binary log format.

    When mixed logging is enabled, the server uses a combination of statement-based logging and row-based logging. Statement-based logging is used where possible, but when the server determines a statement may not be safe for statement-based logging, it will use row-based logging instead. See for a list of unsafe statements.

    During one transaction, some statements may be logged with row logging while others are logged with statement-based logging.

    This mode can be enabled by setting the system variable to MIXED.

    Row-Based Logging

    When row-based logging is enabled, DML statements are not logged to the . Instead, each insert, update, or delete performed by the statement for each row is logged to the separately. DDL statements are still logged to the .

    Row-based logging uses more storage than the other log formats but is the safest to use. In practice should be as safe.

    If one wants to be able to see the original query that was logged, one can enable , that is shown with , with . This option is on by default.

    This mode can be enabled by setting the system variable to ROW.

    Things to be aware of with row-based logging

    When using row base logging, some statement works different on the master.

    • DELETE FROM table_name

      • In row base mode the table will always use deletion row-by-row which can take a long time if the table is big. It can also use a lot of space in the binary log.

      • In STATEMENT or MIXED mode, will be used, if possible (no triggers, no foreign keys etc). This is much faster and uses less space in the binary log.

    Compression of the Binary Log

    can be used with any of the binary log formats, but the best results come from using mixed or row-based logging. You can enable compression by using the startup option.

    Configuring the Binary Log Format

    The format for events can be configured by setting the system variable. If you have the privilege, then you can change it dynamically with . For example:

    You can also change it dynamically for just a specific session with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Be careful when changing the binary log format when using . When you change the binary log format on a server, it only changes the format for that server. Changing the binary log format on a primary has no effect on the replica's binary log format. This can cause replication to give inconsistent results or to fail.

    Be careful changing the binary log format dynamically when the server is a replica and is enabled. If you change the global value dynamically, then that does not also affect the session values of any currently running threads. This can cause problems with , because the will remain running even after is executed. This can be worked around by resetting the system variable. For example:

    For considerations when replicating temporary tables, see .

    Effect of the Binary Log Format on Replicas

    A replica will apply any events it gets from the primary, regardless of the binary log format. The system variable only applies to normal (not replicated) updates.

    If you are running MySQL or an older MariaDB than 10.0.22, you should be aware of that if you are running the replica in binlog_format=STATEMENT mode, the replica will stop if the primary is used with binlog_format set to anything else than STATEMENT.

    The binary log format is upwards-compatible. This means replication should always work if the replica is the same or a newer version of MariaDB than the primary.

    The mysql Database

    Statements that affect the mysql database can be logged in a different way to that expected.

    If the mysql database is edited directly, logging is performed as expected according to the . Statements that directly edit the mysql database include , , , , , , , and .

    If the mysql database is edited indirectly, statement logging is used regardless of setting. Statements editing the mysql database indirectly include , , , , , and (except for the situation described below).

    CREATE TABLE ... SELECT can use a combination of logging formats. The portion of the statement is logged using statement-based logging, while the portion is logged according to the value of binlog_format.

    See Also

    This page is licensed: CC BY-SA / Gnu FDL

    General Query Log

    Describes the General Query Log, a comprehensive record of every query and connection event received by the server, useful for auditing and debugging but potentially high-volume.

    The general query log is a log of every SQL query received from a client, as well as each client connect and disconnect. Since it's a record of every query received by the server, it can grow large quite quickly.

    However, if you only want a record of queries that change data, it might be better to use the instead. One important difference is that the only logs a query when the transaction is committed by the server, but the general query log logs a query immediately when it is received by the server.

    Enabling the General Query Log

    The general query log is disabled by default.

    To enable the general query log, set the

    Using and Maintaining the Binary Log

    Best practices for managing binary logs, including setting expiration policies (`expire_logs_days`), purging old logs, and using the `mysqlbinlog` utility.

    See for a general overview of what the binary log is and for how to make sure it's running on your system.

    For details on using the binary log for replication, see the section.

    Purging Log Files

    To delete all binary log files on the server, run the command. To delete all binary logs before a certain datetime, or up to a certain number, use .

    If a replica is active but has yet to read from a binary log file you attempt to delete, the statement will fail with an error. However, if the replica is not connected and has yet to read from a log file you delete, the file will be deleted, but the replica will be unable to continue replicating once it connects again.

    shell> ls -l 
    total 100
    ...
    -rw-rw---- 1 mysql adm 2098 Apr 19 00:46 mariadb-bin.000079
    -rw-rw---- 1 mysql adm  332 Apr 19 00:56 mariadb-bin.000080
    -rw-rw---- 1 mysql adm  347 Apr 19 07:36 mariadb-bin.000081
    -rw-rw---- 1 mysql adm  306 Apr 20 07:15 mariadb-bin.000082
    -rw-rw---- 1 mysql adm  332 Apr 20 07:41 mariadb-bin.000083
    -rw-rw---- 1 mysql adm  373 Apr 21 07:56 mariadb-bin.000084
    -rw-rw---- 1 mysql adm  347 Apr 21 09:09 mariadb-bin.000085
    -rw-rw---- 1 mysql adm  398 Apr 21 21:24 mariadb-bin.000086
    -rw-rw---- 1 mysql adm  816 Apr 21 17:05 mariadb-bin.index
    SET sql_log_bin = 0;
    
    SET sql_log_bin = 1;
    system variable to 1. It can be changed dynamically with
    . For example:

    It can also be set in a server option group in an option file prior to starting up the server. For example:

    Configuring the General Query Log Filename

    By default, the general query log is written to ${hostname}.log in the datadir directory. However, this can be changed.

    One way to configure the general query log filename is to set the general_log_file system variable. It can be changed dynamically with SET GLOBAL. For example:

    It can also be set in a server option group in an option file prior to starting up the server. For example:

    If it is a relative path, then the general_log_file is relative to the datadir directory.

    However, the general_log_file system variable can also be an absolute path. For example:

    Another way to configure the general query log filename is to set the log-basename option, which configures MariaDB to use a common prefix for all log files (e.g. general query log, slow query log, error log, binary logs, etc.). The general query log filename will be built by adding a .log extension to this prefix. This option cannot be set dynamically. It can be set in a server option group in an option file prior to starting up the server. For example:

    The log-basename cannot be an absolute path. The log file name is relative to the datadir directory.

    Choosing the General Query Log Output Destination

    The general query log can either be written to a file on disk, or it can be written to the general_log table in the mysql database. To choose the general query log output destination, set the log_output system variable.

    Writing the General Query Log to a File

    The general query log is output to a file by default. However, it can be explicitly chosen by setting the log_output system variable to FILE. It can be changed dynamically with SET GLOBAL. For example:

    It can also be set in a server option group in an option file prior to starting up the server. For example:

    Writing the General Query Log to a Table

    The general query log can either be written to the general_log table in the mysql database by setting the log_output system variable to TABLE. It can be changed dynamically with SET GLOBAL. For example:

    It can also be set in a server option group in an option file prior to starting up the server. For example:

    Some rows in this table might look like this:

    See Writing logs into tables for more information.

    Disabling the General Query Log for a Session

    A user with the SUPER privilege can disable logging to the general query log for a connection by setting the SQL_LOG_OFF system variable to 1. For example:

    Disabling the General Query Log for Specific Statements

    In and later, it is possible to disable logging to the general query log for specific types of statements by setting the log_disabled_statements system variable. This option cannot be set dynamically. It can be set in a server option group in an option file prior to starting up the server. For example:

    Rotating the General Query Log on Unix and Linux

    Unix and Linux distributions offer the logrotate utility, which makes it very easy to rotate log files. See Rotating Logs on Unix and Linux for more information on how to use this utility to rotate the general query log.

    See Also

    • MariaDB audit plugin

    This page is licensed: CC BY-SA / Gnu FDL

    binary log
    binary log
    general_log
    SET GLOBAL

    Log files can also be removed automatically with the expire_logs_days system variable. This is set to 0 by default (no removal), but can be set to a time, in days, after which a binary log file will be automatically removed. Log files will only be checked for being older than expire_logs_days upon log rotation, so if your binary log only fills up slowly and does not reach max_binlog_size on a daily basis, you may see older log files still being kept. You can also force log rotation, and so expiry deletes, by running FLUSH BINARY LOGS on a regular basis. Always set expire_logs_days higher than any possible replica lag.

    From , the binlog_expire_logs_seconds variable allows more precise control over binlog deletion and takes precedence if both are non-zero.

    If the binary log index file has been removed, or incorrectly manually edited, all of the above forms of purging log files will fail. The .index file is a plain text file and can be manually recreated or edited so that it lists only the binary log files that are present, in numeric/age order.

    Examples

    Safely Purging Binary Log Files While Replicating

    To be sure replication is not broken while deleting log files, perform the following steps:

    • Get a listing of binary log files on the primary by running SHOW BINARY LOGS.

    • Go to each replica server and run SHOW SLAVE STATUS to check which binary log file each replica is currently reading.

    • Find the earliest log file still being read by a replica. No log files before this one will be needed.

    • If you wish, make a backup of the log files to be deleted

    • Purge all log files before (not including) the file identified above.

    Limiting the Binlog Size

    MariaDB starting with

    From , it's possible to limit the size of the binlog by setting the max_binlog_total_size system variable. If not set to zero, the total size of the binlog will be stored in the binlog_disk_use status variable. It's also possible to limit the size of a single binlog file by setting max_binlog_size.

    Binary Log Format

    There are three formats for the binary log. The default is statement-based logging, while row-based logging and a mix of the two formats are also possible. See Binary Log Formats for a full discussion.

    Selectively Logging to the Binary Log

    By default, all changes to data or data structure are logged. This behavior can be changed by starting the server with the --binlog-ignore-db=database_name or --binlog-do-db=database_name options.

    --binlog-ignore-db=database_name specified a database to ignore for logging purposes, while --binlog-do-db=database_name will not log any statements unless they apply to the specified database.

    Neither option accepts comma-delimited lists of multiple databases as an option, since a database name can contain a comma. To apply to multiple databases, use the option multiple times.

    --binlog-ignore-db=database_name behaves differently depending on whether statement-based or row-based logging is used. For statement-based logging, the server will not log any statement where the default database is database_name. The default database is set with the USE statement.

    Similarly, --binlog-do-db=database_name also behaves differently depending on whether statement-based or row-based logging is used.

    For statement-based logging, the server will only log statement where the default database is database_name. The default database is set with the USE statement.

    For row-based logging, the server will log any updates to any tables in the named database/s, irrespective of the current database.

    Examples

    Assume the server has started with the option --binlog-ignore-db=employees. The following example is logged if statement-based logging is used, and is not logged with row-based logging.

    This is because statement-based logging examines the default database, in this case, customers. Since customers is not specified in the ignore list, the statement will be logged. If row-based logging is used, the example will not be logged as updates are written to the tables in the employees database.

    Assume instead the server started with the option --binlog-do-db=employees. The following example is not logged if statement-based logging is used, and is logged with row-based logging.

    This is again because statement-based logging examines the default database, in this case, customers. Since customers is not specified in the do list, the statement will not be logged. If row-based logging is used, the example will be logged as updates are written to the tables in the employees database.

    Effects of Full Disk Errors on Binary Logging

    If MariaDB encounters a full disk error while trying to write to a binary log file, then it will keep retrying the write every 60 seconds. Log messages will get written to the error log every 600 seconds. For example:

    However, if MariaDB encounters a full disk error while trying to open a new binary log file, then it will disable binary logging entirely. A log message like the following will be written to the error log:

    See Also

    • PURGE LOGS

    This page is licensed: CC BY-SA / Gnu FDL

    Overview of the Binary Log
    Activating the Binary Log
    Replication
    RESET MASTER
    PURGE BINARY LOGS
    binary log
    mariadb-binlog
    binary log
    mixed logging
    row logging
    binary log
    binlog_format
    ALTER TABLE
    S3 storage engine
    SEQUENCEs
    CREATE TABLE
    replication
    Unsafe Statements for Statement-based Replication
    Mixed logging
    Unsafe Statements for Statement-based Replication: Unsafe Statements
    binlog_format
    binary log
    binary log
    binary log
    mixed logging
    annotated rows events
    mariadb-binlog
    --binlog-annotate-row-events
    binlog_format
    truncate
    Compression of the binary log
    --log_bin_compress
    binary log
    binlog_format
    SUPER
    SET GLOBAL
    SET SESSION
    option group
    option file
    replication
    parallel replication
    parallel replication
    worker threads
    STOP SLAVE
    slave_parallel_threads
    Replicating temporary tables
    binlog_format
    binlog_format
    INSERT
    UPDATE
    DELETE
    REPLACE
    DO
    LOAD DATA INFILE
    SELECT
    TRUNCATE TABLE
    binlog_format
    GRANT
    REVOKE
    SET PASSWORD
    RENAME USER
    ALTER
    DROP
    CREATE
    CREATE TABLE
    SELECT
    Setting up replication
    Compressing the binary log
    Replicating temporary tables
    SET GLOBAL general_log=1;
    [mariadb]
    ...
    general_log
    SET GLOBAL general_log_file='mariadb.log';
    [mariadb]
    ...
    general_log
    general_log_file=mariadb.log
    [mariadb]
    ...
    general_log
    general_log_file=/var/log/mysql/mariadb.log
    [mariadb]
    ...
    log-basename=mariadb
    general_log
    SET GLOBAL log_output='FILE';
    [mariadb]
    ...
    log_output=FILE
    general_log
    general_log_file=queries.log
    SET GLOBAL log_output='TABLE';
    [mariadb]
    ...
    log_output=TABLE
    general_log
    SELECT * FROM mysql.general_log\G
    *************************** 1. row ***************************
      event_time: 2014-11-11 08:40:04.117177
       user_host: root[root] @ localhost []
       thread_id: 74
       server_id: 1
    command_type: Query
        argument: SELECT * FROM test.s
    *************************** 2. row ***************************
      event_time: 2014-11-11 08:40:10.501131
       user_host: root[root] @ localhost []
       thread_id: 74
       server_id: 1
    command_type: Query
        argument: SELECT * FROM mysql.general_log
    ...
    SET SESSION SQL_LOG_OFF=1;
    [mariadb]
    ...
    log_output=FILE
    general_log
    general_log_file=queries.log
    log_disabled_statements='slave,sp'
    PURGE BINARY LOGS TO 'mariadb-bin.000063';
    PURGE BINARY LOGS BEFORE '2013-04-22 09:55:22';
    USE customers;
    UPDATE employees.details SET bonus=bonus*1.2;
    USE customers;
    UPDATE employees.details SET bonus=bonus*1.2;
    2018-11-27  2:46:46 140278181563136 [Warning] mysqld: Disk is full writing '/var/lib/mariadb-bin.00001' (Errcode: 28 "No space left on device"). Waiting for someone to free space... (Expect up to 60 secs delay for server to continue after freeing disk space)
    2018-11-27  2:46:46 140278181563136 [Warning] mysqld: Retry in 60 secs. Message reprinted in 600 secs
    2018-11-27  3:30:49 140278181563136 [ERROR] Could not open '/var/lib/mariadb-bin.00002 for logging (error 28). Turning logging off for the whole duration of the MySQL server process. To turn it on again: fix the cause, shutdown the MySQL server and restart it.
    2018-11-27  3:30:49 140278181563136 [ERROR] mysqld: Error writing file '(null)' (errno: 9 "Bad file descriptor")
    2018-11-27  3:30:49 140278181563136 [ERROR] mysqld: Error writing file '(null)' (errno: 28 "No space left on device")
    [Warning] Unsafe statement written to the binary log using statement format since 
      BINLOG_FORMAT = STATEMENT. The statement is unsafe because it uses a LIMIT clause. 
      This is unsafe because the set of rows included cannot be predicted.
    SET GLOBAL binlog_format='ROW';
    SET SESSION binlog_format='ROW';
    [mariadb]
    ...
    binlog_format=ROW
    STOP SLAVE;
    SET GLOBAL slave_parallel_threads=0;
    SET GLOBAL binlog_format='ROW';
    SET GLOBAL slave_parallel_threads=4;
    START SLAVE

    SQL Error Log Plugin

    Documentation for the SQL Error Log Plugin, which allows logging of errors sent to clients to a file, enabling analysis of application-side errors that might otherwise be missed.

    The SQL_ERROR_LOG plugin collects errors sent to clients in a log file defined by sql_error_log_filename, so that they can later be analyzed. The log file can be rotated if sql_error_log_rotate is set.

    Errors are logged as they happen and an error will be logged even if it was handled by a condition handler and was never technically sent to the client.

    From warnings can also be logged if sql_error_log_warnings is enabled.

    Comments are also logged, which can make the log easier to search. But this is only possible if the client does not strip the comments away. For example, the mariadb command-line client only leaves comments when started with the --comments option.

    Installing the Plugin

    Although the plugin's shared library is distributed with MariaDB by default, the plugin is not actually installed by MariaDB by default. There are two methods that can be used to install the plugin with MariaDB.

    The first method can be used to install the plugin without restarting the server. You can install the plugin dynamically by executing or . For example:

    The second method can be used to tell the server to load the plugin when it starts up. The plugin can be installed this way by providing the or the options. This can be specified as a command-line argument to or it can be specified in a relevant server in an . For example:

    Uninstalling the Plugin

    You can uninstall the plugin dynamically by executing or . For example:

    If you installed the plugin by providing the or the options in a relevant server in an , then those options should be removed to prevent the plugin from being loaded the next time the server is restarted.

    Logging

    The log format until is:

    Starting from , the format is:

    Starting from , , , , , , and , when the variable is enabled, the log also contains thread id and database name. If there is no database, NULL will be displayed.

    Each separated by a space or : as above

    Option
    Description
    Version

    Example of Logs

    With enabled (database test and thread id 4):

    Example Usage

    Versions

    Version
    Status
    Introduced

    System Variables and Options

    This page is licensed: CC BY-SA / Gnu FDL

    Group Commit for the Binary Log

    Describes the group commit optimization, which improves performance by committing multiple transactions to the binary log in a single disk I/O operation.

    Overview

    The server supports group commit. This is an important optimization that helps MariaDB reduce the number of expensive disk operations that are performed.

    Durability

    In ACID terminology, the "D" stands for durability. In order to ensure durability with group commit, and/or should be set. These settings are needed to ensure that if the server crashes, then any transaction that was committed prior to the time of crash will still be present in the database after crash recovery.

    Durable InnoDB Data and Binary Logs

    Setting both and provides the most durability and the best guarantee of consistency after a crash.

    Non-Durable InnoDB Data

    If is set, but is not set to 1 or 3, then it is possible after a crash to end up in a state where a transaction present in a server's is missing from the server's . If the server is a , then that means that the server can become inconsistent with its replicas, since the replicas may have replicated transactions from the primary's that are no longer present in the primary's local data.

    Non-Durable Binary Logs

    If is set to 1 or 3, but is not set, then it is possible after a crash to end up in a state where a transaction present in a server's is missing from the server's . If the server is a , then that also means that the server can become inconsistent with its replicas, since the server's replicas would not be able to replicate the missing transactions from the server's .

    Non-Durable InnoDB Data and Binary Logs

    Setting when is not set can also cause the transaction to be missing from the server's due to some optimizations added in those versions. In that case, it is recommended to always set . If you can't do that, then it is recommended to set to 3, rather than 1. See for more information.

    Amortizing Disk Flush Costs

    After every transaction , the server normally has to flush any changes the transaction made to the and the to disk (i.e. by calling system calls such as fsync() or fdatasync() or similar). This helps ensure that the data changes made by the transaction are stored durably on the disk. Disk flushing is a time-consuming operation, and can easily impose limits on throughput in terms of the number of transactions-per-second (TPS) which can be committed.

    The idea with group commit is to amortize the costs of each flush to disk over multiple commits from multiple parallel transactions. For example, if there are 10 transactions trying to commit in parallel, then we can force all of them to be flushed disk at once with a single system call, rather than do one system call for each commit. This can greatly reduce the need for flush operations, and can consequently greatly improve the throughput of transactions-per-second (TPS).

    However, to see the positive effects of group commit, the workload must have sufficient parallelism. A good rule of thumb is that at least three parallel transactions are needed for group commit to be effective. For example, while the first transaction is waiting for its flush operation to complete, the other two transactions will queue up waiting for their turn to flush their changes to disk. When the first transaction is done, a single system call can be used to flush the two queued-up transactions, saving in this case one of the three system calls.

    In addition to sufficient parallelism, it is also necessary to have enough transactions per second wanting to commit that the flush operations are a bottleneck. If no such bottleneck exists (i.e. transactions never or rarely need to wait for the flush of another to complete), then group commit will provide little to no improvement.

    Changing Group Commit Frequency

    The frequency of group commits can be changed by configuring the and system variables.

    Measuring Group Commit Ratio

    Two status variables are available for checking how effective group commit is at reducing flush overhead. These are the and status variables. We can obtain those values with the following query:

    is the total number of transactions committed to the .

    is the total number of groups committed to the . As explained in the previous sections of this page, a group commit is when a group of transactions is flushed to the together by sharing a single flush system call. When is set, then this is also the total number of flush system calls executed in the process of flushing commits to the .

    Thus the extent to which group commit is effective at reducing the number of flush system calls on the binary log can be determined by the ratio between these two status variables. will always be as equal to or greater than . The greater the difference is between these status variables, the more effective group commit was at reducing flush overhead.

    To calculate the group commit ratio, we actually need the values of these status variables from two snapshots. Then we can calculate the ratio with the following formula:

    transactions/group commit = (Binlog_commits (snapshot2) - Binlog_commits (snapshot1))/(Binlog_group_commits (snapshot2) - Binlog_group_commits (snapshot1))

    For example, if we had the following first snapshot:

    And the following second snapshot:

    Then we would have:

    transactions/group commit = (220 - 120) / (145 - 120) = 100 / 25 = 4 transactions/group commit

    If your group commit ratio is too close to 1, then it may help to .

    Use of Group Commit with Parallel Replication

    Group commit is also used to enable .

    Effects of Group Commit on InnoDB Performance

    When both (the default) is set and the is enabled, there is now one less sync to disk inside InnoDB during commit (2 syncs shared between a group of transactions instead of 3). See for more information.

    Status Variables

    is the total number of transactions committed to the .

    is the total number of groups committed to the .

    is the total number of group commits triggered because of the number of commits in the group reached the limit set by the system variable .

    is the total number of group commits triggered because a commit was being delayed because of a lock wait where the lock was held by a prior binary log commit. When this happens the later binary log commit is placed in the next group commit.

    is the total number of group commits triggered because of the time since the first commit reached the limit set by the system variable .

    To query these variables, use a statement such as:

    See Also

    This page is licensed: CC BY-SA / Gnu FDL

    Transaction Coordinator Log Overview

    Explains the purpose of the Transaction Coordinator (TC) log (`tc.log`), which maintains consistency for XA transactions that affect multiple storage engines, and how to configure it.

    The transaction coordinator log (tc_log) is used to coordinate transactions that affect multiple XA-capable storage engines. If you have two or more XA-capable storage engines enabled, then a transaction coordinator log must be available.

    Types of Transaction Coordinator Logs

    There are currently two implementations of the transaction coordinator log:

    • Binary log-based transaction coordinator log

    • Memory-mapped file-based transaction coordinator log

    If the is enabled on a server, then the server will use the binary log-based transaction coordinator log. Otherwise, it will use the memory-mapped file-based transaction coordinator log.

    Binary Log-Based Transaction Coordinator Log

    This transaction coordinator uses the , which is enabled by the server option.

    Memory-Mapped File-Based Transaction Coordinator Log

    This transaction coordinator uses the memory-mapped file defined by the server option. The size is defined by the system variable.

    Some facts about this log:

    • The log consists of a memory-mapped file that is divided into pages of 8KB size.

    • The usable size of the first page is smaller because of the log header. There is a PAGE control structure for each page.

    • Each page (or rather its PAGE control structure) can be in one of the three states - active, syncing, pool.

    • There could be only one page in the active or syncing state, but many in the pool state - pool is a fifo queue.

    The result of such an architecture is a natural "commit grouping" - If commits are coming faster than the system can sync, they do not stall. Instead, all commits that came since the last sync are logged to the same "active" page, and they all are synced with the next - one - sync. Thus, thought individual commits are delayed, throughput is not decreasing.

    When an xid is added to an active page, the thread of this xid waits for a page's condition until the page is synced. When a syncing slot becomes vacant one of these waiters is awakened to take care of syncing. It syncs the page and signals all waiters that the page is synced. The waiters are counted, and a page may never become active again until waiters==0, which means that is all waiters from the previous sync have noticed that the sync was completed.

    Note that a page becomes "dirty" and has to be synced only when a new xid is added into it. Removing a xid from a page does not make it dirty - we don't sync xid removals to disk.

    Monitoring the Memory-Mapped File-Based Transaction Coordinator Log

    The memory-mapped transaction coordinator log can be monitored with the following status variables:

    Heuristic Recovery with the Transaction Coordinator Log

    One of the main purposes of the transaction coordinator log is in crash recovery. See for more information about that.

    Known Issues

    You must enable exactly N storage engines

    Prior to , if you were using the memory-mapped file-based transaction coordinator log, and then if the server crashed and you changed the number of XA-capable storage engines that it loaded, then you could see errors like the following:

    To recover from this error, delete the file defined by the server option, and then restart the server with the option set.

    See for more information.

    Bad magic header in tc log

    If you are using the memory-mapped file-based transaction coordinator log, then it is possible to see errors like the following:

    This means that the header of the memory-mapped file-based transaction coordinator log is corrupt. To recover from this error, delete the file defined by the --log-tc server option, and then restart the server with the --tc-heuristic-recover option set.

    This issue is known to occur when using docker. In that case, the problem may be caused by using a MariaDB container version with a data directory from a different MariaDB or MySQL version. Therefore, some potential fixes are:

    • Pinning the docker instance to a specific MariaDB version in the docker compose file, so that it consistently uses the same version.

    • Running to ensure that the data directory is upgraded to match the server version.

    See for more information.

    MariaDB Galera Cluster

    builds include a built-in plugin called wsrep. Prior to , this plugin was internally considered an . Consequently, these MariaDB Galera Cluster builds have multiple XA-capable storage engines by default, even if the only "real" storage engine that supports external enabled on these builds by default is . Therefore, when using one these builds MariaDB would be forced to use a transaction coordinator log by default, which could have performance implications.

    For example, describes performance problems where MariaDB Galera Cluster actually performs better when the is enabled. It is possible that this is caused by the fact that MariaDB is forced to use the memory-mapped file-based transaction coordinator log in this case, which may not perform as well.

    This became a bigger issue in when the patch that powers MariaDB Galera Cluster was enabled on most MariaDB builds on Linux by default. Consequently, this built-in wsrep plugin would exist on those MariaDB builds on Linux by default. Therefore, MariaDB users might pay a performance penalty, even if they never actually intended to use the MariaDB Galera Cluster features included in .

    In and later, the built-in wsrep plugin has been changed to a replication plugin. Therefore, it is no longer considered an storage engine, so it no longer forces MariaDB to use a transaction coordinator log by default.

    See for more information.

    This page is licensed: CC BY-SA / Gnu FDL

    innodb_flush_log_at_trx_commit=1
    sync_binlog=1
    innodb_flush_log_at_trx_commit=1
    sync_binlog=1
    replication
    sync_binlog=1
    innodb_flush_log_at_trx_commit
    binary log
    InnoDB redo log
    replication primary
    binary log
    InnoDB
    innodb_flush_log_at_trx_commit
    sync_binlog=1
    InnoDB redo log
    binary log
    replication primary
    binary log
    innodb_flush_log_at_trx_commit=1
    sync_binlog=1
    InnoDB redo log
    sync_binlog=1
    innodb_flush_log_at_trx_commit
    Non-durable Binary Log Settings
    COMMIT
    InnoDB redo log
    binary log
    binlog_commit_wait_usec
    binlog_commit_wait_count
    Binlog_commits
    Binlog_group_commits
    Binlog_commits
    binary log
    Binlog_group_commits
    binary log
    binary log
    sync_binlog=1
    binary log
    Binlog_commits
    Binlog_group_commits
    change your group commit frequency
    conservative mode of in-order parallel replication
    innodb_flush_log_at_trx_commit=1
    binary log
    Binary Log Group Commit and InnoDB Flushing Performance
    Binlog_commits
    binary log
    Binlog_group_commits
    binary log
    Binlog_group_commit_trigger_count
    binary log
    binlog_commit_wait_count
    Binlog_group_commit_trigger_lock_wait
    binary log
    Binlog_group_commit_trigger_timeout
    binary log
    binlog_commit_wait_usec
    Parallel Replication
    Binary Log Group Commit and InnoDB Flushing Performance
    Group commit benchmark
    SHOW GLOBAL STATUS WHERE Variable_name IN('Binlog_commits', 'Binlog_group_commits');
    SHOW GLOBAL STATUS WHERE Variable_name IN('Binlog_commits', 'Binlog_group_commits');
    +----------------------+-------+
    | Variable_name        | Value |
    +----------------------+-------+
    | Binlog_commits       | 120   |
    | Binlog_group_commits | 120   |
    +----------------------+-------+
    2 rows in set (0.00 sec)
    SHOW GLOBAL STATUS WHERE Variable_name IN('Binlog_commits', 'Binlog_group_commits');
    +----------------------+-------+
    | Variable_name        | Value |
    +----------------------+-------+
    | Binlog_commits       | 220   |
    | Binlog_group_commits | 145   |
    +----------------------+-------+
    2 rows in set (0.00 sec)
    SHOW GLOBAL STATUS LIKE 'Binlog_%commit%';

    Type

    ERROR or WARNING

    10.11.6

    Error_code

    OS error, MariaDB storage engine code (120-199) or MariaDB internal error code (1000-)

    5.5.22

    Query

    Query text

    5.5.22

    sql_error_log_rotations
  • sql_error_log_size_limit

  • sql_error_log_size_warnings

  • sql_error_log_with_db_and_thread_info

  • Time

    Time (YYYY-MM-DD hh-mm-ss)

    5.5.22

    Thread Id

    Thread Id of current thread

    10.6.17

    User

    privilege_user [login_user_name] @ hostname [ip]

    5.5.22

    Database name

    Name of the currently selected database

    10.6.17

    1.1

    Stable

    , , , ,

    1.0

    Stable

    1.0

    Gamma

    1.0

    Alpha

    INSTALL SONAME
    INSTALL PLUGIN
    --plugin-load
    --plugin-load-add
    mariadbd
    option group
    option file
    UNINSTALL SONAME
    UNINSTALL PLUGIN
    --plugin-load
    --plugin-load-add
    option group
    option file
    MariaDB 10.11
    sql_error_log_with_db_and_thread_info
    sql_error_log_with_db_and_thread_info
    sql_error_log
    sql_error_log_filename
    sql_error_log_rate
    sql_error_log_rotate

    The usual lifecycle of a page is pool->active->syncing->pool.

  • The "active" page is a page where new xid's are logged.

  • The page stays active as long as the syncing slot is taken.

  • The "syncing" page is being synced to disk. no new xid can be added to it.

  • When the syncing is done the page is moved to a pool and an active page becomes "syncing".

  • binary log
    binary log
    log_bin
    --log-tc
    log_tc_size
    Tc_log_max_pages_used
    Tc_log_page_size
    Tc_log_page_waits
    Heuristic Recovery with the Transaction Coordinator Log
    --log-tc
    --tc-heuristic-recover
    MDEV-9214
    mariadb-upgrade
    this docker issue
    XA-capable
    storage engine
    XA transactions
    InnoDB
    MDEV-16509
    binary log
    MySQL-wsrep
    XA-capable
    MDEV-16442

    Rotating Logs on Unix and Linux

    A guide to using the `logrotate` utility on Linux to manage MariaDB log files, ensuring they don't consume excessive disk space by rotating, compressing, and archiving them.

    Unix and Linux distributions offer the logrotate utility, which makes it very easy to rotate log files. This page will describe how to configure log rotation for the error log, general query log, and the slow query log.

    Configuring Locations and File Names of Logs

    The first step is to configure the locations and file names of logs. To make the log rotation configuration easier, it can be best to put these logs in a dedicated log directory.

    We will need to configure the following:

    • The location and file name is configured with the system variable.

    • The location and file name is configured with the system variable.

    • The location and file name is configured with the system variable.

    If you want to enable the and immediately, then you will also have to configure the following:

    • The is enabled with the system variable.

    • The is enabled with the system variable.

    These options can be set in a server in an prior to starting up the server. For example, if we wanted to put our log files in /var/log/mysql/, then we could configure the following:

    We will also need to create the relevant directory:

    If you are using , then you may also need to set the SELinux context for the directory. See for more information. For example:

    After MariaDB is restarted, it will use the new log locations and file names.

    Configuring Authentication for Logrotate

    The utility needs to be able to authenticate with MariaDB in order to flush the log files.

    The easiest way to allow the utility to authenticate with MariaDB is to configure the root@localhost user account.

    Note

    The root@localhost user account is configured to use unix_socket authentication by default

    The root@localhost user account can be altered to use authentication with the statement. For example:

    <>

    Configuring Logrotate

    At this point, we can configure the utility to rotate the log files.

    On many systems, the primary configuration file is located at the following path:

    • /etc/logrotate.conf

    And the configuration files for individual services are located in the following directory:

    • /etc/logrotate.d/

    We can create a configuration file for MariaDB by executing the following command in a shell:

    You may have to modify this configuration file to use it on your system, depending on the specific version of the utility that is installed. See the description of each configuration directive below to determine which versions support that configuration directive.

    Each specific configuration directive does the following:

    • missingok: This directive configures it to ignore missing files, rather than failing with an error.

    • create 660 mysql mysql: This directive configures it to recreate the log files after log rotation with the specified permissions and owner.

    • notifempty: This directive configures it to skip a log file during log rotation if it is empty.

    If our system does not have 3.8.9 or later, which is needed to support the createolddir directive, then we will also need to create the relevant directory specified by the olddir directive:

    Testing Log Rotation

    We can test log rotation by executing the utility with the --force option. For example:

    Keep in mind that under normal operation, the utility may skip a log file during log rotation if the utility does not believe that the log file needs to be rotated yet. For example:

    • If you set the notifempty directive mentioned above, then it will be configured to skip a log file during log rotation if the log file is empty.

    • If you set the daily directive mentioned above, then it will be configured to only rotate each log file once per day.

    • If you set the minsize 1M directive mentioned above, then it will be configured to skip a log file during log rotation if the log file size is smaller than 1 MB.

    However, when running tests with the --force option, the utility does not take these options into consideration.

    After a few tests, we can see that the log rotation is indeed working:

    Logrotate in Ansible

    Let's see an example of how to configure logrotate in Ansible.

    First, we'll create a couple of tasks in our playbook:

    The first task creates a directory to store the old, compressed logs, and set proper permissions.

    The second task uploads logrotate configuration file into the proper directory, and calls it mysql. As you can see the original name is different, and it ends with the .j2 extension, because it is a Jinja 2 template.

    The file will look like the following:

    The file is very similar to the file shown above, which is obvious because we're still uploading a logrotate configuration file. Ansible is just a tool we've chosen to do this.

    However, both in the tasks and in the template, we used some variables. This allows to use different paths and rotation parameters for different hosts, or host groups.

    If we have a group host called mariadb that contains the default configuration for all our MariaDB servers, we can define these variables in a file called group_vars/mariadb.yml:

    After setting up logrotate in Ansible, you may want to deploy it to a non-production server and test it manually as explained above. Once you're sure that it works fine on one server, you can be confident in the new Ansible tasks and deploy them on all servers.

    For more information on how to use Ansible to automate MariaDB configuration, see .

    This page is licensed: CC BY-SA / Gnu FDL

    INSTALL SONAME 'sql_errlog';
    [mariadb]
    ...
    plugin_load_add = sql_errlog
    UNINSTALL SONAME 'sql_errlog';
    Time User Error_code: Error_message : Query
    Time User Type Error_code: Error_message : Query
    Time Thread_id User Database_name Type Error_code: Error_message : Query
    2023-10-31 15:54:37 root[root] @ localhost [] ERROR 1146: Table 'test.t_doesnt_exist' doesn't exist : select * from t_doesnt_exist
    2023-10-31 15:54:37 root[root] @ localhost [] ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'syntax_error_query' at line 1 : syntax_error_query
    2023-10-31 15:54:37 root[root] @ localhost [] ERROR 1146: Table 'test.temptab' doesn't exist : SELECT `c` FROM `temptab`
    2023-11-01 11:31:15 [monty] @ storm [192.168.0.12] ERROR 1051: Unknown table 'test.t1' : drop table t1
    2023-10-31 15:54:37 4 root[root] @ localhost [] `test` ERROR 1146: Table 'test.t_doesnt_exist' doesn't exist : select * from t_doesnt_exist
    install plugin SQL_ERROR_LOG soname 'sql_errlog';
    Query OK, 0 rows affected (0.00 sec)
    
    USE test;
    
    SET sql_mode='STRICT_ALL_TABLES,NO_ENGINE_SUBSTITUTION';
    Query OK, 0 rows affected (0.00 sec)
    
    CREATE TABLE foo2 (id INT) ENGINE=WHOOPSIE;
    ERROR 1286 (42000): Unknown storage engine 'WHOOPSIE'
    \! cat data/sql_errors.log
    2013-03-19  9:38:40 msandbox[msandbox] @ localhost [] ERROR 1286: Unknown storage engine 'WHOOPSIE' : CREATE TABLE foo2 (id int) ENGINE=WHOOPSIE
    2018-11-30 23:08:49 140046048638848 [Note] Recovering after a crash using tc.log          
    2018-11-30 23:08:49 140046048638848 [ERROR] Recovery failed! You must enable exactly 3 storage engines that support two-phase commit protocol
    2018-11-30 23:08:49 140046048638848 [ERROR] Crash recovery failed. Either correct the problem (if it's, for example, out of memory error) and restart, or delete tc log and start mysqld with --tc-heuristic-recover={commit|rollback}
    2018-11-30 23:08:49 140046048638848 [ERROR] Can't init tc log
    2018-11-30 23:08:49 140046048638848 [ERROR] Aborting
    2018-09-19  4:29:31 0 [Note] Recovering after a crash using tc.log                                                               
    2018-09-19  4:29:31 0 [ERROR] Bad magic header in tc log
    2018-09-19  4:29:31 0 [ERROR] Crash recovery failed. Either correct the problem (if it's, for example, out of memory error) and restart, or delete tc log and start mysqld with --tc-heuristic-recover={commit|rollback}                                           
    2018-09-19  4:29:31 0 [ERROR] Can't init tc log
    2018-09-19  4:29:31 0 [ERROR] Aborting

    daily: This directive configures it to rotate each log file once per day.

  • minsize 1M: This directive configures it to skip a log file during log rotation if it is smaller than 1 MB. This directive is only available with logrotate 3.7.4 and later.

  • maxsize 100M: This directive configures it to rotate a log file more frequently than daily if it grows larger than 100 MB. This directive is only available with logrotate 3.8.1 and later.

  • rotate 30: This directive configures it to keep 30 old copies of each log file.

  • dateext: This directive configures it to use the date as an extension, rather than just a number. This directive is only available with logrotate 3.7.6 and later.

  • dateformat .%Y-%m-%d-%H-%M-%S: This directive configures it to use this date format string (as defined by the format specification for strftime) for the date extension configured by the dateext directive. This directive is only available with logrotate 3.7.7 and later. Support for %H is only available with logrotate 3.9.0 and later. Support for %M and %S is only available with logrotate 3.9.2 and later.

  • compress: This directive configures it to compress the log files with gzip.

  • delaycompress: This directive configures it to delay compression of each log file until the next log rotation. If the log file is compressed at the same time that it is rotated, then there may be cases where a log file is being compressed while the MariaDB server is still writing to the log file. Delaying compression of a log file until the next log rotation can prevent race conditions such as these that can happen between the compression operation and the MariaDB server's log flush operation.

  • olddir archive/: This directive configures it to archive the rotated log files in /var/log/mysql/archive/.

  • createolddir 770 mysql mysql: This directive configures it to create the directory specified by the olddir directive with the specified permissions and owner, if the directory does not already exist. This directive is only available with logrotate 3.8.9 and later.

  • sharedscripts: This directive configures it to run the postrotate script just once, rather than once for each rotated log file.

  • postrotate: This directive configures it to execute a script after log rotation. This particular script executes the mariadb-admin utility, which executes the FLUSH statement, which tells the MariaDB server to flush its various log files. When MariaDB server flushes a log file, it closes its existing file handle and reopens a new one. This ensure that MariaDB server does not continue writing to a log file after it has been rotated. This is an important component of the log rotation process.

  • error log
    log_error
    general query log
    general_log_file
    slow query log
    slow_query_log_file
    general query log
    slow query log
    general query log
    general_log
    slow query log
    slow_query_log
    option group
    option file
    SELinux
    SELinux: Setting the File Context for Log Files
    logrotate
    logrotate
    unix_socket
    ALTER USER
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    logrotate
    Ansible and MariaDB
    [mariadb]
    ...
    log_error=/var/log/mysql/mariadb.err
    general_log
    general_log_file=/var/log/mysql/mariadb.log
    slow_query_log
    slow_query_log_file=/var/log/mysql/mariadb-slow.log
    long_query_time=5
    sudo mkdir /var/log/mysql/
    sudo chown mysql:mysql /var/log/mysql/
    sudo chmod 0770 /var/log/mysql/
    sudo semanage fcontext -a -t mysqld_log_t "/var/log/mysql(/.*)?"
    sudo restorecon -Rv /var/log/mysql
    ALTER USER 'root'@'localhost' IDENTIFIED VIA unix_socket;
    $ sudo tee /etc/logrotate.d/mariadb <<EOF
    /var/log/mysql/* {
            su mysql mysql
            missingok
            create 660 mysql mysql
            notifempty
            daily
            minsize 1M # only use with logrotate >= 3.7.4
            maxsize 100M # only use with logrotate >= 3.8.1
            rotate 30
            # dateext # only use if your logrotate version is compatible with below dateformat
            # dateformat .%Y-%m-%d-%H-%M-%S # only use with logrotate >= 3.9.2
            compress
            delaycompress
            sharedscripts 
            olddir archive/
            createolddir 770 mysql mysql # only use with logrotate >= 3.8.9
        postrotate
            # just if mysqld is really running
            if test -x /usr/bin/mysqladmin && \
               /usr/bin/mysqladmin ping &>/dev/null
            then
               /usr/bin/mysqladmin --local flush-error-log \
                  flush-engine-log flush-general-log flush-slow-log
            fi
        endscript
    }
    EOF
    sudo mkdir /var/log/mysql/archive/
    sudo chown mysql:mysql /var/log/mysql/archive/
    sudo chmod 0770 /var/log/mysql/archive/
    sudo logrotate --force /etc/logrotate.d/mariadb
    $ sudo ls -l /var/log/mysql/archive/
    total 48
    -rw-rw---- 1 mysql mysql  440 Mar 31 15:31 mariadb.err.1
    -rw-rw---- 1 mysql mysql  138 Mar 31 15:30 mariadb.err.2.gz
    -rw-rw---- 1 mysql mysql  145 Mar 31 15:28 mariadb.err.3.gz
    -rw-rw---- 1 mysql mysql 1007 Mar 31 15:27 mariadb.err.4.gz
    -rw-rw---- 1 mysql mysql 1437 Mar 31 15:32 mariadb.log.1
    -rw-rw---- 1 mysql mysql  429 Mar 31 15:31 mariadb.log.2.gz
    -rw-rw---- 1 mysql mysql  439 Mar 31 15:28 mariadb.log.3.gz
    -rw-rw---- 1 mysql mysql  370 Mar 31 15:27 mariadb.log.4.gz
    -rw-rw---- 1 mysql mysql 3915 Mar 31 15:32 mariadb-slow.log.1
    -rw-rw---- 1 mysql mysql  554 Mar 31 15:31 mariadb-slow.log.2.gz
    -rw-rw---- 1 mysql mysql  569 Mar 31 15:28 mariadb-slow.log.3.gz
    -rw-rw---- 1 mysql mysql  487 Mar 31 15:27 mariadb-slow.log.4.gz
    - name: Create mariadb_logrotate_old_dir
      file:
        path: "{{ mariadb_logrotate_old_dir }}"
        owner: mysql
        group: mysql
        mode: '770'
        state: directory
    
    - name: Configure logrotate
      template:
        src: "../templates/logrotate.j2"
        dest: "/etc/logrotate.d/mysql"
    {{ mariadb_log_dir }}/* {
            su mysql mysql
            missingok
            create 660 mysql mysql
            notifempty
            daily
            minsize 1M {{ mariadb_logrotate_min_size }}
            maxsize 100M {{ mariadb_logrotate_max_size }}
            rotate {{ mariadb_logrotate_old_dir }}
            dateformat .%Y-%m-%d-%H-%M-%S # only use with logrotate >= 3.9.2
            compress
            delaycompress
            sharedscripts 
            olddir archive/
            createolddir 770 mysql mysql # only use with logrotate >= 3.8.9
        postrotate
            # just if mysqld is really running
            if test -x /usr/bin/mysqladmin && \
               /usr/bin/mysqladmin ping &>/dev/null
            then
               /usr/bin/mysqladmin --local flush-error-log \
                  flush-engine-log flush-general-log flush-slow-log
            fi
        endscript
    }
    # MariaDB writes its logs here
    mariadb_log_dir: /var/lib/mysql/logs
    
    # logrotate configuration
    
    mariadb_logrotate_min_size: 500M
    mariadb_logrotate_max_size: 1G
    mariadb_logrotate_old_files: 7
    mariadb_logrotate_old_dir: /var/mysql/old-logs

    Slow Query Log Overview

    Explains how to enable and configure the slow query log to identify queries that take longer than a specified time (`long_query_time`) or don't use indexes.

    The slow query log is a record of SQL queries that took a long time to perform.

    Note that, if your queries contain user's passwords, the slow query log may contain passwords too. Thus, it should be protected.

    The number of rows affected by the slow query are also recorded in the slow query log.

    Enabling the Slow Query Log

    The slow query log is disabled by default.

    To enable the slow query log, set the slow_query_log system variable (or, from MariaDB 10.11, log_slow_query) to 1. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Configuring the Slow Query Log Filename

    By default, the slow query log is written to ${hostname}-slow.log in the directory. However, this can be changed.

    One way to configure the slow query log filename is to set the system variable (or, from , ). It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    If it is a relative path, then the is relative to the directory.

    However, the system variable can also be an absolute path. For example:

    Another way to configure the slow query log filename is to set the option, which configures MariaDB to use a common prefix for all log files (e.g. slow query log, , , , etc.). The slow query log filename will be built by adding -slow.log to this prefix. This option cannot be set dynamically. It can be set in a server in an prior to starting up the server. For example:

    The cannot be an absolute path. The log file name is relative to the directory.

    Choosing the Slow Query Log Output Destination

    The slow query log can either be written to a file on disk, or it can be written to the table in the database. To choose the slow query log output destination, set the system variable.

    Writing the Slow Query Log to a File

    The slow query log is output to a file by default. However, it can be explicitly chosen by setting the system variable to FILE. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Writing the Slow Query Log to a Table

    The slow query log can either be written to the table in the database by setting the system variable to TABLE. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Some rows in this table might look like this:

    See for more information.

    Disabling the Slow Query Log for a Session

    A user can disable logging to the slow query log for a connection by setting the system variable (or, from , ) to 0. For example:

    Disabling the Slow Query Log for Specific Statements

    It is possible to disable logging to the slow query log for specific types of statements by setting the system variable. This option cannot be set dynamically. It can be set in a server in an prior to starting up the server. For example:

    Configuring the Slow Query Log Time

    The time that defines a slow query can be configured by setting the system variable (or, from , ). It uses a units of seconds, with an optional milliseconds component. The default value is 10. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Logging Queries That Don't Use Indexes

    It can be beneficial to log queries that don't use indexes to the slow query log, since queries that don't use indexes can usually be optimized either by adding an index or by doing a slight rewrite. The slow query log can be configured to log queries that don't use indexes regardless of their execution time by adding the option "not_using_index" to or setting the system variable to 1. It can be changed dynamically with . Some examples:

    It can also be set in a server in an prior to starting up the server. For example:

    As a significant number of queries can run quickly even without indexes, you can use the system variable (or, from , ) with to limit the logged queries to those having a material impact on the server.

    Excluding Queries That Examine Fewer Than a Minimum Row Limit

    It can be beneficial to exclude queries that examine fewer than a minimum number of rows from the log. This can be done by setting the system variable, or, from , . It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Logging Slow Administrative Statements

    By default, the Slow Query Log logs administrative statements. To disable logging of administrative statements, remove "admin" from the system variable or alternatively set the system variable to OFF. The Slow Query Log considers the following statements administrative: , , , , , , and . In and later, this also includes statements.

    You can dynamically enable this feature using a statement and setting it for just the current connection with LOCAL. Some examples:

    It can also be set in a server in an prior to starting up the server. For example:

    Enabling the Slow Query Log for Specific Criteria

    It is possible to enable logging to the slow query log for queries that meet specific criteria by configuring the system variable. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    You can find all options for log_slow_filter at or at .

    Throttling the Slow Query Log

    The slow query log can create a lot of I/O, so it can be beneficial to throttle it in some cases. The slow query log can be throttled by configuring the system variable. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    Configuring the Slow Query Log Verbosity

    There are a few optional pieces of information that can be included in the slow query log for each query. This optional information can be included by configuring the system variable. It can be changed dynamically with . For example:

    It can also be set in a server in an prior to starting up the server. For example:

    It is possible to have .

    Viewing the Slow Query Log

    Slow query logs written to file can be viewed with any text editor, or you can use the tool to ease the process by summarizing the information.

    Queries that you find in the log are key queries to try to optimize by constructing a or by making .

    For queries that appear in the log that cannot be optimized in the above ways, perhaps because they are simply very large selects, due to slow hardware, or very high lock/cpu/io contention, using shard/clustering/load balancing solutions, better hardware, or stats tables may help to improve these queries.

    Slow query logs written to table can be viewed by querying the table.

    Variables Related to the Slow Query Log

    • - enable/disable the slow query log. Renamed to from .

    • - how the output will be written

    • . Whether to log OPTIMIZE, ANALYZE, ALTER and other administrative statements to the slow log. Deprecated from , use without admin.

    • - name of the slow query log file. Renamed to

    Rotating the Slow Query Log on Unix and Linux

    Unix and Linux distributions offer the utility, which makes it very easy to rotate log files. See for more information on how to use this utility to rotate the slow query log.

    This page is licensed: CC BY-SA / Gnu FDL

    Error Log

    Details the Error Log, which captures critical server errors, warnings, and startup/shutdown messages, and explains how to configure its verbosity and output destination (file or syslog).

    The error log contains a record of critical errors that occurred during the server's operation, table corruption, start and stop information.

    SQL errors can also be logged in a separate file using the .

    Configuring the Error Log Output Destination

    MariaDB always writes its error log, but the destination is configurable.

    from
    .
  • long_query_time - time in seconds/microseconds defining a slow query. Renamed to log_slow_query_time from MariaDB 10.11.0.

  • log_queries_not_using_indexes - whether to log queries that don't use indexes

  • log_slow_admin_statements - whether to log certain admin statements

  • log_slow_disabled_statements - types of statements that should not be logged in the slow query log

  • min_examined_row_limit - minimum rows a query must examine to be slow. Renamed to log_slow_min_examined_row_limit from MariaDB 10.11.0.

  • log_slow_rate_limit - permits a fraction of slow queries to be logged

  • log_slow_verbosity - amount of detail in the log

  • log_slow_filter - limit which queries to log

  • log_slow_slave_statements - log slow statements executed by replica thread to the slow log if it is open.

  • SET GLOBAL
    option group
    option file
    datadir
    slow_query_log_file
    MariaDB 10.11
    log_slow_query_file
    SET GLOBAL
    option group
    option file
    slow_query_log_file
    datadir
    slow_query_log_file
    log-basename
    general query log
    error log
    binary logs
    option group
    option file
    log-basename
    datadir
    slow_log
    mysql
    log_output
    log_output
    SET GLOBAL
    option group
    option file
    slow_log
    mysql
    log_output
    SET GLOBAL
    option group
    option file
    Writing logs into tables
    slow_query_log
    MariaDB 10.11
    log_slow_query
    log_slow_disabled_statements
    option group
    option file
    long_query_time
    MariaDB 10.11
    log_slow_query_time
    SET GLOBAL
    option group
    option file
    log_slow_filter
    log_queries_not_using_indexes
    SET GLOBAL
    option group
    option file
    min_examined_row_limit
    MariaDB 10.11
    log_slow_min_examined_row_limit
    log_queries_not_using_indexes
    min_examined_row_limit
    MariaDB 10.11
    log_slow_min_examined_row_limit
    SET GLOBAL
    option group
    option file
    log_slow_filter
    log_slow_admin_statements
    ALTER TABLE
    ANALYZE TABLE
    CHECK TABLE
    CREATE INDEX
    DROP INDEX
    OPTIMIZE TABLE
    REPAIR TABLE
    ALTER SEQUENCE
    SET GLOBAL
    option group
    option file
    log_slow_filter
    SET GLOBAL
    option group
    option file
    log_slow_filter system variable
    Slow Query Log Extended Statistics
    log_slow_rate_limit
    SET GLOBAL
    option group
    option file
    log_slow_verbosity
    SET GLOBAL
    option group
    option file
    EXPLAIN output printed in the slow query log
    mariadb-dumpslow
    more efficient query
    better use of indexes
    slow_log
    slow_query_log
    log_slow_query
    MariaDB 10.11
    log_output
    log_slow_admin_statements
    log_slow_filter
    slow_query_log_file
    log_slow_query_file_name
    logrotate
    Rotating Logs on Unix and Linux
    MariaDB 10.11.0
    Writing the Error Log to a File

    To configure the error log to be written to a file, you can set the log_error system variable. You can configure a specific file name. However, if a specific file name is not configured, the log will be written to the ${hostname}.err file in the datadir directory by default.

    The log_error system variable can be set in a server option group in an option file prior to starting up the server. For example, to write the error log to the default ${hostname}.err file, you could configure the following:

    If you configure a specific file name as the log_error system variable, and if it is not an absolute path, then it will be relative to the datadir directory. For example, if you configured the following, then the error log would be written to mariadb.err in the datadir directory:

    If it is a relative path, then the log_error is relative to the datadir directory.

    However, the log_error system variable can also be an absolute path:

    Another way to configure the error log file name is to set the log-basename option, which configures MariaDB to use a common prefix for all log files (e.g. general query log, slow query log, error log, binary logs, etc.). The error log file name will be built by adding a .err extension to this prefix. For example, if you configured the following, then the error log would still be written to mariadb.err in the datadir directory:

    The log-basename cannot be an absolute path. The log file name is relative to the datadir directory.

    Writing the Error Log to Stderr on Unix

    On Unix, if the log_error system variable is not set, errors are written to stderr, which usually means that the log messages are output to the terminal that started mariadbd.

    If the log_error system variable was set in an option file or on the command-line, it can still be unset by specifying --skip-log-error.

    Writing the Error Log to Syslog on Unix

    On Unix, the error log can also be redirected to the syslog. How this is done depends on how you start MariaDB.

    Syslog with mariadbd-safe

    If you start MariaDB with mariadbd-safe, the error log can be redirected to the syslog. See mariadbd-safe: Configuring MariaDB to Write the Error Log to Syslog for more information.

    Syslog with Systemd

    If you start MariaDB with systemd, the error log can also be redirected to the syslog. See Systemd: Configuring MariaDB to Write the Error Log to Syslog for more information.

    systemd also has its own logging system called the journal, and some errors may get logged there instead. See Systemd:Systemd Journal for more information.

    Writing the Error Log to Console on Windows

    On Windows, if the console option is specified, and if the log_error system variable is not used, errors are written to the console. If both options are specified, the last option takes precedence.

    Writing the Error Log to the Windows Event Viewer

    On Windows, error log messages are also written to the Windows Event Viewer. You can find MariaDB's error log messages by browsing Windows Logs, then selecting Application or Application Log, depending on the Windows version.

    You can find MariaDB's error log messages by searching for the Source MariaDB (prior to , this was MySQL).

    Finding the Error Log

    To find where the error log is stored, one can find the options used for the error log with:

    or (from )

    or

    If the above don't help, check also if your system is set to write to syslog, in which case you need to use journalctl to access it.

    Configuring the Error Log Verbosity

    The default value of the log_warnings system variable is 2.

    The log_warnings system variable can be used to configure the verbosity of the error log. It can be changed dynamically with SET GLOBAL. For example:

    It can also be set either on the command-line or in a server option group in an option file prior to starting up the server. For example:

    Some of the warnings included in each verbosity level are described below.

    The log_warnings system variable only has an effect on some log messages. Some log messages are always written to the error log, regardless of the error log verbosity. For example, most warnings from the InnoDB storage engine are not affected by log_warnings. For a complete list of log messages affected by log_warnings, see the description of the log_warnings system variable.

    Verbosity Level 0

    If log_warnings is 0, many optional warnings will not be logged. However, this does not prevent all warnings from being logged, because there are certain core warnings that will always be written to the error log. For example:

    • If InnoDB strict mode is disabled, and if DDL is performed on a table that triggers a "Row size too large" error, InnoDB logs a warning:

    However, if InnoDB strict mode is enabled, the same message will be logged as an error.

    Verbosity Level 1

    Default until . If log_warnings is 1, many types of warnings are logged. Some useful warnings are:

    • Replication-related messages:

    • Messages related to DNS lookup failures:

    • Messages related to the event scheduler:

    • Messages related to unsafe statements for statement-based replication:

    Frequent warnings about unsafe statements for statement-based replication can cause the error log to grow very large. MariaDB will automatically detect frequent duplicate warnings about unsafe statements for statement-based replication. After 10 identical warnings are detected, MariaDB will prevent that same warning from being written to the error log again for the next 5 minutes.

    Verbosity Level 2

    Default from . If log_warnings is 2, a couple other different kinds of warnings are printed. For example:

    • Messages related to access denied errors:

    • Messages related to connections that are aborted due to errors or timeouts:

    • Messages related to table handler errors:

    • Messages related to the files used to persist replication state:

      • Either the default master.info file or the file that is configured by the master_info_file option.

      • Either the default relay-log.info file or the file that is configured by the relay_log_info_file system variable.

    • Messages about a master's binary log dump thread:

    Verbosity Level 3

    If log_warnings is 3, a couple other different kinds of warnings are printed. For example:

    • Messages related to old-style language options:

    • Messages related to progress of InnoDB online DDL:

    Verbosity Level 4

    If log_warnings is 4, a couple other different kinds of warnings are printed. For example:

    • Messages related to killed connections:

    • Messages related to all closed connections:

    • Messages related to released connections, such as when a transaction is committed and completion_type is set to RELEASE:

    Verbosity Level 9

    If log_warnings is 9, some very verbose warnings are printed. For example:

    • Messages about initializing plugins:

    MySQL's log_error_verbosity

    MariaDB does not support the log_error_verbosity system variable added in MySQL 5.7.

    Format

    The error log begins with a line indicating where the data is being read from, for example:

    Then, each item (note, warning or error) consists of a single line, containing the date (yyyy-mm-dd) and time, the thread ID, followed by the type of error (Note, Warning or Error) and the error message, for example:

    Until , the format only consisted of the date (yymmdd) and time, followed by the type of error (Note, Warning or Error) and the error message, for example:

    The first item will always contain the source revision, a unique server id (from , , , , , , , ) and the process_id, for example:

    or

    Rotating the Error Log on Unix and Linux

    Unix and Linux distributions offer the logrotate utility, which makes it very easy to rotate log files. See Rotating Logs on Unix and Linux for more information on how to use this utility to rotate the error log.

    Error Messages File

    Many error messages are read from an error message file that contains localized error messages. If the server can't find this file when it starts up, you might see errors like the following:

    If this error is occurring because the file is in a custom location, you can configure this location by setting the lc_messages_dir system variable either on the command-line or in a server option group in an option file prior to starting up the server:

    If you want to use a different locale for error messages, you can also set the lc_messages system variable:

    See Setting the Language for Error Messages for more information.

    See Also

    • sql error log plugin

    This page is licensed: CC BY-SA / Gnu FDL

    SQL_ERROR_LOG plugin
    SET GLOBAL slow_query_log=1;
    [mariadb]
    ...
    slow_query_log
    SET GLOBAL slow_query_log_file='mariadb-slow.log';
    [mariadb]
    ...
    slow_query_log
    slow_query_log_file=mariadb-slow.log
    [mariadb]
    ...
    slow_query_log
    slow_query_log_file=/var/log/mysql/mariadb-slow.log
    [mariadb]
    ...
    log-basename=mariadb
    slow_query_log
    SET GLOBAL log_output='FILE';
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    SET GLOBAL log_output='TABLE';
    [mariadb]
    ...
    log_output=TABLE
    slow_query_log
    SELECT * FROM mysql.slow_log\G
    ...
    *************************** 2. row ***************************
        start_time: 2014-11-11 07:56:28.721519
         user_host: root[root] @ localhost []
        query_time: 00:00:12.000215
         lock_time: 00:00:00.000000
         rows_sent: 1
     rows_examined: 0
                db: test
    last_insert_id: 0
         insert_id: 0
         server_id: 1
          sql_text: SELECT SLEEP(12)
         thread_id: 74
    ...
    SET SESSION slow_query_log=0;
    [mariadb]
    ...
    log_output=FILE
    general_log
    general_log_file=queries.log
    log_slow_disabled_statements='admin,call,slave,sp'
    SET GLOBAL long_query_time=5.0;
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    SET @@log_slow_filter=concat(@@log_slow_filter,",not_using_index");
    SET GLOBAL log_queries_not_using_indexes=ON;
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    log_queries_not_using_indexes=ON
    SET GLOBAL min_examined_row_limit=100000;
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    min_examined_row_limit=100000
    SET SESSION log_slow_filter=replace(@@log_slow_filter,"admin","");
    SET GLOBAL log_slow_admin_statements=ON;
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    log_slow_admin_statements=ON
    SET GLOBAL log_slow_filter='filesort,filesort_on_disk,tmp_table,tmp_table_on_disk';
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    log_slow_filter=filesort,filesort_on_disk,tmp_table,tmp_table_on_disk
    SET GLOBAL log_slow_rate_limit=5;
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    log_slow_rate_limit=5
    SET GLOBAL log_slow_verbosity='full';
    [mariadb]
    ...
    log_output=FILE
    slow_query_log
    slow_query_log_file=slow-queries.log
    long_query_time=5.0
    log_slow_verbosity=query_plan,explain,engine
    [mariadb]
    ...
    log_error
    [mariadb]
    ...
    log_error=mariadb.err
    [mariadb]
    ...
    log_error=/var/log/mysql/mariadb.err
    [mariadb]
    ...
    log-basename=mariadb
    log_error
    mariadbd --print-defaults
    my_print_defaults --mariadbd | grep log-error
    my_print_defaults --mysqld | grep log-error
    SET GLOBAL log_warnings=3;
    [mariadb]
    ...
    log_warnings=3
    [Warning] InnoDB: Cannot add field col25 in table db1.tab because after 
      adding it, the row size is 8477 which is greater than maximum allowed 
      size (8126) for a record on index leaf page.
    [Note] Error reading relay log event: slave SQL thread was killed
    [Note] Slave SQL thread exiting, replication stopped in log 
      'dbserver-2-bin.000033'   at position 181420; 
      GTID position '0-263316466-368886'
    [Note] Slave I/O thread exiting, read up to log 
      'dbserver-2-bin.000034', position 642; 
      GTID position 0-263316466-368887
    [Warning] IP address '192.168.1.193' 
      could not be resolved: Name or service not known
    [Note] Event Scheduler: Loaded 0 events
    [Warning] Unsafe statement written to the binary log using statement format since 
      BINLOG_FORMAT = STATEMENT. The statement is unsafe because 
      it uses a LIMIT clause. This 
      is unsafe because the set of rows included cannot be predicted.
    [Warning] Access denied for user 'root'@'localhost' (using password: YES)
    [Warning] Aborted connection 35 to db: 'unconnected' user: 
      'user1@host1' host: '192.168.1.40' (Got an error writing communication packets)
    [Warning] Aborted connection 36 to db: 'unconnected' user: 
      'user1@host2' host: '192.168.1.230' (Got an error writing communication packets)
    [Warning] Aborted connection 38 to db: 'db1' user: 
      'user2' host: '192.168.1.60' (Unknown error) 
    [Warning] Aborted connection 51 to db: 'db1' user: 
      'user2' host: '192.168.1.50' (Got an error reading communication packets)
    [Warning] Aborted connection 52 to db: 'db1' user: 
      'user3' host: '192.168.1.53' (Got timeout reading communication packets)
    [Warning] Can't find record in 'tab1'.
    [Warning] Can't write; duplicate key in table 'tab1'.
    [Warning] Lock wait timeout exceeded; try restarting transaction.
    [Warning] The number of locks exceeds the lock table size.
    [Warning] Update locks cannot be acquired during a READ UNCOMMITTED transaction.
    [Note] Reading Master_info: '/mariadb/data/master.info'  
      Relay_info:'/mariadb/data/relay-log.info'
    [Note] Initialized Master_info from '/mariadb/data/master.info'
    [Note] Reading of all Master_info entries succeded
    [Note] Deleted Master_info file '/mariadb/data/master.info'.
    [Note] Deleted Master_info file '/mariadb/data/relay-log.info'.
    [Note] Start binlog_dump to slave_server(263316466), pos(, 4)
    [Warning] An old style --language value with language specific 
      part detected: /usr/local/mysql/data/
    [Warning] Use --lc-messages-dir without language specific part instead.
    [Note] InnoDB: Online DDL : Start
    [Note] InnoDB: Online DDL : Start reading clustered index of the table and 
      create temporary files
    [Note] InnoDB: Online DDL : End of reading clustered index of the table and 
      create temporary files
    [Note] InnoDB: Online DDL : Start merge-sorting index PRIMARY (1 / 3), 
      estimated cost : 18.0263
    [Note] InnoDB: Online DDL : merge-sorting has estimated 33 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 1 estimated 33 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 2 estimated 17 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 3 estimated 9 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 4 estimated 5 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 5 estimated 3 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 6 estimated 2 runs
    [Note] InnoDB: Online DDL : End of  merge-sorting index PRIMARY (1 / 3)
    [Note] InnoDB: Online DDL : Start building index PRIMARY (1 / 3), 
      estimated cost : 27.0395
    [Note] InnoDB: Online DDL : End of building index PRIMARY (1 / 3)
    [Note] InnoDB: Online DDL : Completed
    [Note] InnoDB: Online DDL : Start merge-sorting index ux1 (2 / 3), 
      estimated cost : 5.7895
    [Note] InnoDB: Online DDL : merge-sorting has estimated 2 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 1 estimated 2 runs
    [Note] InnoDB: Online DDL : End of  merge-sorting index ux1 (2 / 3)
    [Note] InnoDB: Online DDL : Start building index ux1 (2 / 3), 
      estimated cost : 8.6842
    [Note] InnoDB: Online DDL : End of building index ux1 (2 / 3)
    [Note] InnoDB: Online DDL : Completed
    [Note] InnoDB: Online DDL : Start merge-sorting index ix1 (3 / 3), 
      estimated cost : 6.1842
    [Note] InnoDB: Online DDL : merge-sorting has estimated 3 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 1 estimated 3 runs
    [Note] InnoDB: Online DDL : merge-sorting current run 2 estimated 2 runs
    [Note] InnoDB: Online DDL : End of  merge-sorting index ix1 (3 / 3)
    [Note] InnoDB: Online DDL : Start building index ix1 (3 / 3), 
      estimated cost : 9.2763
    [Note] InnoDB: Online DDL : End of building index ix1 (3 / 3)
    [Note] InnoDB: Online DDL : Completed
    [Warning] Aborted connection 53 to db: 'db1' user: 
      'user2' host: '192.168.1.50' (KILLED)
    [Warning] Aborted connection 56 to db: 'db1' user: 
      'user2' host: '192.168.1.50' (CLOSE_CONNECTION)
    [Warning] Aborted connection 58 to db: 'db1' user: 
      'user2' host: '192.168.1.50' (RELEASE)
    [Note] Initializing built-in plugins
    [Note] Initializing plugins specified on the command line
    [Note] Initializing installed plugins
    240919 22:58:50 mysqld_safe Starting mariadbd daemon with databases from /home/ian/sandboxes/msb_11_7_0/data
    2016-06-15 16:53:33 139651251140544 [Note] InnoDB: The InnoDB memory heap is disabled
    160615 16:53:08 [Note] InnoDB: The InnoDB memory heap is disabled
    2024-09-19 22:58:50 0 [Note] Starting MariaDB 11.7.0-preview-MariaDB source revision 
      7391f7143b462b29ecdaee049c5ebdfd1aefa6d7 server_uid UdJQ5BCzAQiTopMoCz3yYsfU1lA= 
      as process 2307166
    2024-05-18 16:05:33 0 [Note] Starting MariaDB 10.11.8-MariaDB source revision 
      3a069644682e336e445039e48baae9693f9a08ee as process 50774
    [ERROR] Can't find messagefile '/usr/share/errmsg.sys'
    [mariadb]
    ...
    lc_messages_dir=/usr/share/mysql/
    [mariadb]
    ...
    lc_messages_dir=/usr/share/mysql/
    lc_messages=en_US
    MariaDB Galera Cluster
    MariaDB 10.1
    MariaDB 11.7
    MariaDB 10.5.2
    MariaDB 10.2.4
    MariaDB 10.3.1
    MariaDB 10.6
    11.4
    MariaDB 11.4
    MariaDB 10.1.10
    MariaDB 10.4.3
    MariaDB 10.1
    MariaDB 10.1
    MariaDB 10.4.3
    MariaDB 10.11.5
    MariaDB 10.10
    MariaDB 10.6.17
    MariaDB 10.11.7
    MariaDB 11.0.5
    MariaDB 11.1.4
    MariaDB 11.2.3
    MariaDB 11.3.2
    MariaDB 11.4.1
    MariaDB 10.6.17
    MariaDB 10.11.7
    MariaDB 11.0.5
    MariaDB 11.1.4
    MariaDB 11.2.3
    MariaDB 10.1.13
    MariaDB 10.0.10
    MariaDB 5.5.22
    MariaDB 10.3
    MariaDB 11.0
    MariaDB 10.4
    MariaDB 10.11
    MariaDB 10.2.3
    MariaDB 10.2.4
    MariaDB 10.1.4
    MariaDB 10.5.26
    MariaDB 10.6.19
    MariaDB 10.11.9
    MariaDB 11.1.6
    MariaDB 11.2.5
    MariaDB 11.4.3
    MariaDB 11.5.2
    MariaDB 11.6.1