Mariadb лог ошибок

Contents

  1. Configuring the Error Log Output Destination
    1. Writing the Error Log to a File
    2. Writing the Error Log to Stderr on Unix
    3. Writing the Error Log to Syslog on Unix
      1. Syslog with mysqld_safe
      2. Syslog with Systemd
    4. Writing the Error Log to Console on Windows
    5. Writing the Error Log to the Windows Event Viewer
  2. Configuring the Error Log Verbosity
    1. Verbosity Level 0
    2. Verbosity Level 1
    3. Verbosity Level 2
    4. Verbosity Level 3
    5. Verbosity Level 4
    6. Verbosity Level 9
    7. MySQL’s log_error_verbosity
  3. Format
  4. Rotating the Error Log on Unix and Linux
  5. Error Messages File

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 SQL_ERROR_LOG plugin.

Configuring the Error Log Output Destination

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

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, then 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:

[mariadb]
...
log_error

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:

[mariadb]
...
log_error=mariadb.err

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. For example:

[mariadb]
...
log_error=/var/log/mysql/mariadb.err

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:

[mariadb]
...
log-basename=mariadb
log_error

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, then errors are written to stderr, which usually means that the log messages are output to the terminal that started mysqld.

If the log_error system variable was set in an option file or on the command-line, then 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 mysqld_safe

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

Syslog with Systemd

If you start MariaDB with systemd, then 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, then errors are written to the console. If both options are specified, then 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, and then selecting Application or Application Log, depending on the Windows version.

In MariaDB 10.3 and before, you can find MariaDB’s error log messages by searching for the Source MySQL.

In MariaDB 10.4 and later, you can find MariaDB’s error log messages by searching for the Source MariaDB.

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:

SET GLOBAL log_warnings=3;

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:

[mariadb]
...
log_warnings=3

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, then 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, then InnoDB will log a warning:
[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.

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

Verbosity Level 1

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

  • Replication-related messages:
[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
  • Messages related to DNS lookup failures:
[Warning] IP address '192.168.1.193' 
  could not be resolved: Name or service not known
  • Messages related to the event scheduler:
[Note] Event Scheduler: Loaded 0 events
  • Messages related to unsafe statements for statement-based replication:
[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.

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 MariaDB 10.2.4. If log_warnings is 2, then a couple other different kinds of warnings are printed. For example:

  • Messages related to access denied errors:
[Warning] Access denied for user 'root'@'localhost' (using password: YES)
  • Messages related to connections that are aborted due to errors or timeouts:
[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)
  • Messages related to table handler errors:
[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.
  • 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.
[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'.
  • Messages about a master’s binary log dump thread:
[Note] Start binlog_dump to slave_server(263316466), pos(, 4)

Verbosity Level 3

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

  • Messages related to old-style language options:
[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.
  • Messages related to progress of InnoDB online DDL:
[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

Verbosity Level 4

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

  • Messages related to killed connections:
[Warning] Aborted connection 53 to db: 'db1' user: 
  'user2' host: '192.168.1.50' (KILLED)
  • Messages related to all closed connections:
[Warning] Aborted connection 56 to db: 'db1' user: 
  'user2' host: '192.168.1.50' (CLOSE_CONNECTION)
  • Messages related to released connections, such as when a transaction is committed and completion_type is set to RELEASE:
[Warning] Aborted connection 58 to db: 'db1' user: 
  'user2' host: '192.168.1.50' (RELEASE)

Verbosity Level 9

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

  • Messages about initializing plugins:
[Note] Initializing built-in plugins
[Note] Initializing plugins specified on the command line
[Note] Initializing installed plugins

MySQL’s log_error_verbosity

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

Format

The format consists of 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:

2016-06-15 16:53:33 139651251140544 [Note] InnoDB: 
  The InnoDB memory heap is disabled

Until MariaDB 10.1.4, 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:

160615 16:53:08 [Note] InnoDB: The InnoDB memory heap is disabled

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 ready from an error messages file that contains localized error messages. If the server can’t find this file when it starts up, then you might see errors like the following:

[ERROR] Can't find messagefile '/usr/share/errmsg.sys'

If this error is occurring because the file is in a custom location, then 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. For example:

[mariadb]
...
lc_messages_dir=/usr/share/mysql/

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

[mariadb]
...
lc_messages_dir=/usr/share/mysql/
lc_messages=en_US

See Setting the Language for Error Messages for more information.

Error Log for MariaDB Enterprise Server

Topics on this page:

  • Overview

  • Purpose

  • Format

    • Log Levels

  • Location

  • Configuration

    • Configure the Path

    • Configure the Verbosity Level

  • Error Log by MariaDB Server Version

Overview

MariaDB Enterprise Server writes log messages to its error log.

Reference material is available for MariaDB Enterprise Server.

Purpose

The error log is intended for:

  • Monitoring the ES system status

  • Diagnosing problems with queries

  • Diagnosing communication problems between Galera Cluster nodes

  • Diagnosing connection failures

Format

The error log uses the following log format:

timestamp thread id [logging level] message

The fields in each log message are:

Field

Description

timestamp

The timestamp for the log message in the format YYYY-MM-DD HH:MM:SS

thread id

The thread ID

logging level

The log level for the log message

message

The log message.

Log Levels

The error log uses the following log levels in the logging level field:

  • Error

  • Note

  • Warning

Location

By default, the error log is located in the data directory defined by the datadir system variable, and the error log’s file name is HOSTNAME.err, where HOSTNAME is the system’s host name.

You can determine the error log’s file name and location by querying the log_error system variable:

SHOW GLOBAL VARIABLES
   LIKE 'log_error';

Configuration

Several aspects of the error log are configurable.

Configure the Path

The path to the error log is configured by setting the log_error system variable.

The system variable can be set in a configuration file:

[mariadb]
log_error=mariadbd.err

The error log will be created in the data directory defined by the datadir system variable.

The error log can be placed outside of the data directory by setting the log_error system variable to the absolute path of the desired location:

[mariadb]
log_error=/var/log/mariadb/mariadbd.err

If the log_error system variable is set, but no value is provided, the path to the error log is set to HOSTNAME.err, where HOSTNAME is the system’s host name:

[mariadb]
# base name on the system's host name
log_error

Configure the Verbosity Level

The verbosity of the error log is configured by the log_warnings system variable.

The verbosity can be between 0 and 9.

The system variable can be set in a configuration file:

This tutorial shows you how to configure and view different MariaDB logs.
MariaDB is an open-source relational database based on SQL (Structured Query
Language). MariaDB offers various built-in logs. In general, a database is the
basis of almost every backend, and administrators want to log this service.

MariaDB has four main logs with different purpose:

  • Error log: Problems encountered during starting, running, or stopping the
    server. The database always generates records for this log, but the
    destination is configurable. It is useful when you want to analyze the server
    itself.
  • General query logs: Records every connection established with each client.
    This log records every query that the client sent to the server. This log is
    useful to determine client problems. However, the log can grow large quite
    quickly.
  • Binary logs: Record each event that manipulates data in a database. It
    records operations such as table creating, modification of schema, inserting
    new values, or querying tables. These logs are used to backup and recover the
    database.
  • Slow query log: Record of each query, which execution took too much time.
    This log could be useful for the optimisation of slow SQL queries.

In this tutorial, you will do following actions:

  • You will install the MariaDB server, configure and view default error log.
  • You will connect to the MariaDB server, view metadata about general query
    logs,
    enable it and view these logs.
  • You will enable the MariaDB binary logs and list them.
  • You will enable and configure a slow query log, simulate some slow query
    and check this incident in the new log.

🔭 Want to centralize and monitor your MariaDB logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

Prerequisites

You will need:

  • Ubuntu 20.04 distribution including the non-root user with sudo access.
  • The server shouldn’t include the installed MySQL server because there is a
    problem with coexistence with the MariaDB configuration. You can learn how to
    completely remove MySQL from the machine in the following
    article.
  • Basic knowledge of SQL languages (understanding of simple select query
    statement).

Step 1 — Viewing and Configuring Error Log

The MariaDB server is maintained by the command-line program mariadb. This
program manages access to the MariaDB data directory that contains databases and
tables. The problems encountered during mariadb starting, running, or stopping
are recorded as an error log. This log doesn’t include any information about SQL
queries. It is useful for the analysis of the MariaDB server.

Installing MariaDB server

First of all, let’s install the MariaDB server. Ubuntu 20.04 allows to install
the MariaDB from default packages with the apt install (installation requires
sudo privilege):

$ sudo apt update
$ sudo apt install mariadb-server

The first command will update Ubuntu repositories, and the second will download
and install required packages for the MariaDB server. Now, the server is
installed.

Connecting to Server and Viewing the Default Configuration

The error log is always enabled, but the destination of this log is
configurable. Let’s view the default configuration.

You can connect to MariaDB server as a root client:

You will be redirected to MariaDB command-line.

Now, you can view system variables related to the error log by executing command
show variables:

MariaDB> show variables like '%log_error%';

The clause specifies a pattern that should match the variable. In our case, the
pattern '%log_error%' specifies to show variables that contain the string
log_error. You’ll see the program’s output appear on the screen:

Output
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_error     |       |
+---------------+-------+
1 row in set (0.002 sec)

The output shows the global variable log_error. This variable holds the
absolute path to file where are stored error log records. As you can see, it is
by default set to null. As a result, the error log output goes to syslog.

You can disconnect from the server by executing the exit command:

You will be redirected back to the terminal.

Viewing Error Log With Journal

Now, you can view the syslog records related to the MariaDB service with
journalctl:

$ journalctl -u mariadb.service

The option -u with the name of the service MariaDB displays only records
related to this service:

Output
May 19 08:54:02 alice systemd[1]: Started MariaDB 10.5.10 database server.
May 19 08:54:02 alice /etc/mysql/debian-start[17467]: Upgrading MySQL tables if necessary.
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Looking for 'mysql' as: /usr/bin/mysql
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Looking for 'mysqlcheck' as: /usr/bin/mysqlcheck
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 1/7: Checking and upgrading mysql database
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Processing databases
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.column_stats                                 OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.columns_priv                                 OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.db                                           OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.event                                        OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.func                                         OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.global_priv                                  OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.gtid_slave_pos                               OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.help_category                                OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.help_keyword                                 OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.help_relation                                OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.help_topic                                   OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.index_stats                                  OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.innodb_index_stats                           OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.innodb_table_stats                           OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.plugin                                       OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.proc                                         OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.procs_priv                                   OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.proxies_priv                                 OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.roles_mapping                                OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.servers                                      OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.table_stats                                  OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.tables_priv                                  OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.time_zone                                    OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.time_zone_leap_second                        OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.time_zone_name                               OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.time_zone_transition                         OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.time_zone_transition_type                    OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.transaction_registry                         OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 2/7: Installing used storage engines... Skipped
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 3/7: Fixing views
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Processing databases
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: information_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql.user                                         OK
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: performance_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 4/7: Running 'mysql_fix_privilege_tables'
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 5/7: Fixing table and database names
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Processing databases
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: information_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: mysql
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: performance_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 6/7: Checking and upgrading tables
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Processing databases
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: information_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: performance_schema
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: Phase 7/7: Running 'FLUSH PRIVILEGES'
May 19 08:54:05 alice /etc/mysql/debian-start[17470]: OK

The output shows that the syslog stores records about the mariadb server
initialisation, and running.

Configuring Custom Error Log File

If you don’t want to include MariaDB error log into syslog, you can set up a
custom log file. You can configure custom error log file by editing MariaDB
configuration file /etc/mysql/mariadb.conf.d/50-server.cnf (sudo required):

$ sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

The file contains the following lines that hold configuration variable
log_error (by default commented out):

# Enable this if you want to have error logging into a separate file
#log_error = /var/log/mysql/error.log

You can configure a custom error log file by uncommenting the line with the
variable log_error, and set up the absolute path to the log file:

# Enable this if you want to have error logging into a separate file
log_error = /var/log/mariadb/error.log

In our example, we change the default log_error value to the directory
/var/log/mariadb (the Linux default directory for logs). Now, you can save the
file.

Now, let’s create a subdirectory mariadb in the /var/log. You can create the
subdirectory with the command mkdir (sudo required):

$ sudo mkdir /var/log/mariadb

Next, you must set proper access right to this directory for the MariaDB daemon.
You can set up user and group owner of this subdirectory by command chown
(sudo required):

$ sudo chown mysql:mysql /var/log/mariadb

The command chown set directory user to mysql and group to mysql, which is
the proper access rights for the MariaDB daemon.

At last, if you want immediately apply the new configuration rules then you must
restart the MariaDB server with systemctl (sudo required):

$ sudo systemctl restart mariadb.service

Now, the MariaDB server record error log to custom file.

Viewing Custom Error Log

You can view the new file with cat (sudo required because file is maintained
by the system):

$ cat /var/log/mariadb/error.log

You’ll see the program’s output appear on the screen:

Output
2021-05-19 11:17:25 0 [Note] InnoDB: Uses event mutexes
2021-05-19 11:17:25 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2021-05-19 11:17:25 0 [Note] InnoDB: Number of pools: 1
2021-05-19 11:17:25 0 [Note] InnoDB: Using crc32 + pclmulqdq instructions
2021-05-19 11:17:25 0 [Note] mariadbd: O_TMPFILE is not supported on /tmp (disabling future attempts)
2021-05-19 11:17:25 0 [Note] InnoDB: Using Linux native AIO
2021-05-19 11:17:25 0 [Note] InnoDB: Initializing buffer pool, total size = 134217728, chunk size = 134217728
2021-05-19 11:17:25 0 [Note] InnoDB: Completed initialization of buffer pool
2021-05-19 11:17:25 0 [Note] InnoDB: 128 rollback segments are active.
2021-05-19 11:17:25 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2021-05-19 11:17:25 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2021-05-19 11:17:25 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2021-05-19 11:17:25 0 [Note] InnoDB: 10.5.10 started; log sequence number 45214; transaction id 20
2021-05-19 11:17:25 0 [Note] Plugin 'FEEDBACK' is disabled.
2021-05-19 11:17:25 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2021-05-19 11:17:25 0 [Note] InnoDB: Buffer pool(s) load completed at 210519 11:17:25
2021-05-19 11:17:25 0 [Note] Server socket created on IP: '127.0.0.1'.
2021-05-19 11:17:25 0 [Note] Reading of all Master_info entries succeeded
2021-05-19 11:17:25 0 [Note] Added new Master_info '' to hash table
2021-05-19 11:17:25 0 [Note] /usr/sbin/mariadbd: ready for connections.
Version: '10.5.10-MariaDB-1:10.5.10+maria~focal'  socket: '/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution

The output shows records similar to syslog records.

Step 2 — Viewing General Query Logs

The server writes records about each client event during connection to the
general query log. Basically, it keeps the information about all SQL statements
that happened. This log is useful when the administrators want to know what
clients exactly execute. However, keep in mind that the general query log slows
down performance, and administrators usually turn it on only for a short time
for debugging.

Connecting to Server and Checking General Query Log Status

First of all, let’s check the status of the general query log because this
logging feature is usually turned off.

You can connect to MariaDB server as a root client:

You will be redirected to MariaDB command-line.

Now, you can view system variables related to the general query log by executing
command show variables:

MariaDB> show variables like '%general%';

The clause specifies a pattern that should match the variable. In our case, the
pattern '%general%' specifies to show variables that contain the string
general. You’ll see the program’s output appear on the screen:

Output
+------------------+--------------+
| Variable_name    | Value        |
+------------------+--------------+
| general_log      | OFF          |
| general_log_file | alice.log    |
+------------------+--------------+
2 rows in set (0.002 sec)

The output shows two variables:

  • general_log: The variable holds value ON (general log enable), or OFF
    (general log disabled).
  • general_log_file: The variable defines where is the log stored in the file
    system.

As you can see, the general query log is by default disabled. We can disconnect
from the server by executing the exit command:

You will be redirected back to the terminal.

Enabling the General Query Log

You can enable general query log by editing MariaDB configuration file
/etc/mysql/mariadb.conf.d/50-server.cnf (sudo required):

$ sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

The file contains the following lines that hold configuration variables (by
default commented out):

# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# Recommend only changing this at runtime for short testing periods if needed!
#general_log_file       = /var/log/mysql/mysql.log
#general_log            = 1

You can configure a general query log file by uncommenting the lines with these
variables and set up the general_log to 1 (enabled) and general_log_file
to the absolute path to the log file:

# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# Recommend only changing this at runtime for short testing periods if needed!
general_log_file       = /var/log/mariadb/general-query.log
general_log            = 1

In our example, we change the directory to the /var/log/mariadb, same as for
the error log. This directory has already proper access right, as we set in the
previous step.  Now, you can save the file.

Viewing General Query Log

Next, let’s view the content of the new log with a cat (the sudo is required
because this file is maintained by the system):

$ sudo cat /var/log/mariadb/general-query.log

You’ll see the program’s output appear on the screen:

Output
/usr/sbin/mariadbd, Version: 10.5.10-MariaDB-1:10.5.10+maria~focal-log (mariadb.org binary distribution). started with:
Tcp port: 0  Unix socket: /run/mysqld/mysqld.sock
Time                Id Command  Argument
210519 11:58:23      3 Connect  root@localhost on mysql using Socket
                     3 Query    SET SQL_LOG_BIN=0, WSREP_ON=OFF
                     3 Query    show variables like 'datadir'
                     3 Quit
                     4 Connect  root@localhost on  using Socket
                     4 Query    SELECT count(*) FROM mysql.user WHERE user='root' and password='' and plugin in ('', 'mysql_native_password', 'mysql_old_password')
                     4 Quit
                     5 Connect  root@localhost on  using Socket
                     5 Query    select concat('select count(*) into @discard from `',
                    TABLE_SCHEMA, '`.`', TABLE_NAME, '`')
      from information_schema.TABLES where TABLE_SCHEMA<>'INFORMATION_SCHEMA' and TABLE_SCHEMA<>'PERFORMANCE_SCHEMA' and ( ENGINE='MyISAM' or ENGINE='Aria' )
                     5 Quit
                     6 Connect  root@localhost on  using Socket
                     6 Query    select count(*) into @discard from `mysql`.`procs_priv`
                     6 Quit
...

The output shows all statement executed at each session. You can see the
timestamp of the session beginning and the list of SQL queries. There are
already a lot of queries because the system executes them at the server starting
(it retrieves the metadata about the environment).

Step 3 — Enabling and Listing Binary Logs

The binary log contains events that manipulate the database. If you want to
recover the database, you need a backup and a binary log relevant to this
backup. There are multiple binary logs because they are versioned.

Enabling Binary Logs

By default, the binary logs are disabled. You can enable binary logs by editing
MariaDB configuration file /etc/mysql/mariadb.conf.d/50-server.cnf (sudo
required):

$ sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

The file contains the following lines that hold configuration variable log_bin
(by default commented out):

#log_bin                = /var/log/mysql/mysql-bin.log

You can enable binary logging by uncommenting the line with this variable and
set up the log_bin to the absolute path to the directory where you want to
store them:

log_bin                = /var/log/mariadb/binary.log

In our example, we change the directory to the /var/log/mariadb, same as for
the error and general query logs. Now, you can save the file.

Listing Binary Logs

At last, let’s check the binary log configuration in the MariaDB server. Let’s
connect to the MariaDB server as a root client:

You will be redirected to MariaDB prompt.

Now, you can check the binary logs status by executing show binary logs:

MariaDB> show binary logs;

The command will list the binary log files on the server:

Output
+---------------+-----------+
| Log_name      | File_size |
+---------------+-----------+
| binary.000001 |       325 |
+---------------+-----------+
1 row in set (0.000 sec)

The output shows all binary logs. We enable this service just a minute ago, soo
there is just a single file. However, there will be more binary logs indexed
with increasing suffix (for example, binary.000002, binary.000003) Now, we
can find out where are these logs stored.

We can show logs location by executing command show variables:

MariaDB> show variables like '%log_bin%';

We already use this show clause in the previous step. This time, the clause
shows variables that contain the string log_bin. You’ll see the program’s
output appear on the screen:

Output
+---------------------------------+-------------------------------+
| Variable_name                   | Value                         |
+---------------------------------+-------------------------------+
| log_bin                         | ON                            |
| log_bin_basename                | /var/log/mariadb/binary       |
| log_bin_compress                | OFF                           |
| log_bin_compress_min_len        | 256                           |
| log_bin_index                   | /var/log/mariadb/binary.index |
| log_bin_trust_function_creators | OFF                           |
| sql_log_bin                     | ON                            |
+---------------------------------+-------------------------------+
7 rows in set (0.002 sec)

The output shows that the binary logs are stored in directory
/var/log/mariadb, as we set up in the configuration file.

We can disconnect from the server by executing the exit command:

You will be redirected back to the terminal.

Viewing the Binary Log

The binary logs are not plain text files and you can not read them with the text
editor. However, the MariaDB includes command-line utility mysqlbinlog.

You can view the binary log binary.000001 with this utility by executing the
following command (sudo required because the file binary.000001 is
maintained by the system):

$ sudo mysqlbinlog /var/log/mariadb/binary.000001

You’ll see the program’s output appear on the screen:

Output
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#210519 12:10:58 server id 1  end_log_pos 256 CRC32 0xb7f7dbc5  Start: binlog v 4, server v 10.5.10-MariaDB-1:10.5.10+maria~focal-log created 210519 12:10:58 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
MuSkYA8BAAAA/AAAAAABAAABAAQAMTAuNS4xMC1NYXJpYURCLTE6MTAuNS4xMCttYXJpYX5mb2Nh
bC1sb2cAAAAAAAAAAAAy5KRgEzgNAAgAEgAEBAQEEgAA5AAEGggAAAAICAgCAAAACgoKAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAEEwQADQgICAoKCgHF2/e3
'/*!*/;
# at 256
#210519 12:10:58 server id 1  end_log_pos 285 CRC32 0x218f4e3e  Gtid list []
# at 285
#210519 12:10:58 server id 1  end_log_pos 325 CRC32 0x346ae813  Binlog checkpoint binary.000001
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

The output shows an encoded binary log. You can see the warning, which told us
that the log is still in use. You can read about the format and meaning of each
record in this log in the manual pages (man mysqlbinlog). The purpose of the
binary log is to allow replication, as
well as assisting in backup operations.

Step 4 — Configuring Slow Query Log

MariaDB allows to log queries, which took too much time. This mechanism is
called a slow query log. Once again, it is a heavy offload to database
performance, and you should use it just for a short time for database
performance optimisation.

Enabling Slow Query Logging

By default, the slow query log is disabled. You can enable it by editing MariaDB
configuration file /etc/mysql/mariadb.conf.d/50-server.cnf (sudo required):

$ sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

The file contains following lines that holds configuration variables (by default
commented out):

# Enable the slow query log to see queries with especially long duration
#slow_query_log_file    = /var/log/mysql/mariadb-slow.log
#long_query_time        = 10

The slow query log is configured by following three variables:

  • slow_query_log: The slow query logging is disabled (value 0) or enabled
    (value 1).
  • slow_query_log_file: The absolute path to the slow query log. You can
    specify your own file.
  • long_query_time: By default, the slow query logs record each SQL query that
    takes more than 10 seconds. You can change this minimal time interval to
    another value. The value can be specified as a floating-point number where the
    value 1.0 refers to 1 second.

You can enable a slow query log by inserting the new line into the configuration
file with the variable slow_query_log with value 1 (the variable is not
included by default). Also, you can set up your own values to the variables
slow_query_log_file and long_query_time when you uncomment the lines with
these variables:

# Enable the slow query log to see queries with especially long duration
slow_query_log         = 1
slow_query_log_file    = /var/log/mariadb/slow-query.log
long_query_time        = 5

In our example, we change the default long_query_time value to 5 seconds and
set the log file to /var/log/mariadb/slow-query (same directory as for error,
general and binary logs). Now, you can save the file.

Once again, if you want immediately apply the new configuration rules then you
must restart the MariaDB server with systemctl (sudo required):

$ sudo systemctl restart mariadb.service

Now, the MariaDB server enables slow query log.

Checking Slow Query Log Status

You can check that the log is enabled if you login into the MariaDB server as a
root client:

You will be redirected to MariaDB prompt.

Let’s check the slow query log status by executing command show variables:

MariaDB> show variables like '%slow_query_log%';

Once again, we use the show clause. This time, the clause shows variables that
contain the string slow_query_log. You’ll see the program’s output appear on
the screen:

Output
+---------------------+---------------------------------+
| Variable_name       | Value                           |
+---------------------+---------------------------------+
| slow_query_log      | ON                              |
| slow_query_log_file | /var/log/mariadb/slow-query.log |
+---------------------+---------------------------------+
2 rows in set (0.002 sec)

The output shows that the slow query log is enabled (the variable
slow_query_log holds the value ON).

Let’s view actual slow query time interval by executing the command
show variables:

MariaDB> show variables like '%long_query_time%';

You’ll see the program’s output appear on the screen:

Output
+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time |  5.000000 |
+-----------------+-----------+
1 row in set (0.002 sec)

The output shows that the variable long_query_time holds the value 5 seconds
(as we define in the configuration script).

Viewing Slow Query Log

At last, we can check that the MariaDB records slow queries to the new log. You
can execute the following select query that takes 6 seconds:

MariaDB> select sleep(6);

The select will wait 6 seconds and then return 0:

Output
+----------+
| sleep(6) |
+----------+
|        0 |
+----------+
1 row in set (6.001 sec)

The output shows that this query takes 6 seconds. As a result, it should be
recorded in a slow query log.

We can disconnect from the server by executing the exit command:

You will be redirected back to the terminal.

At last, we can print the content of the slow query log
/var/log/mariadb/slow-query.log (the sudo is required because the file is
maintained by the system):

$ sudo cat /var/log/mariadb/slow-query.log

You’ll see the program’s output appear on the screen:

/usr/sbin/mariadbd, Version: 10.5.10-MariaDB-1:10.5.10+maria~focal-log (mariadb.org binary distribution). started with:
Tcp port: 0  Unix socket: /run/mysqld/mysqld.sock
Time            Id Command  Argument
# Time: 210519 14:09:32
# User@Host: root[root] @ localhost []
# Thread_id: 31  Schema:   QC_hit: No
# Query_time: 6.000286  Lock_time: 0.000000  Rows_sent: 1  Rows_examined: 0
# Rows_affected: 0  Bytes_sent: 64
SET timestamp=1621426172;
select sleep(6);

You can see that the output shows record about execution query
select sleep(6).

Conclusion

In this tutorial, you configured and viewed different MariaDB logs. You
installed the MariaDB server, configured and viewed the error log. You
enabled and viewed the general query logs and their configuration. You
enabled and listed binary logs. At last, you enabled, configured and viewed
a slow query log.

Centralize all your logs into one place.

Analyze, correlate and filter logs with SQL.

Create actionable

dashboards.

Share and comment with built-in collaboration.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How To Start Logging With Redis

Learn how to start logging with Redis and go from basics to best practices in no time.

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Журнал ошибок содержит запись критических ошибок,произошедших во время работы сервера,повреждение таблицы,информацию о запуске и остановке.

Ошибки SQL также можно регистрировать в отдельном файле с помощью подключаемого модуля SQL_ERROR_LOG .

Настройка назначения выхода журнала ошибок

MariaDB всегда записывает свой журнал ошибок,но место назначения настраивается.

Запись журнала ошибок в файл.

Чтобы настроить запись журнала ошибок в файл, вы можете установить системную переменную log_error . Вы можете настроить конкретное имя файла. Однако, если конкретное имя файла не настроено, журнал по умолчанию будет записываться в файл ${hostname}.err в каталоге datadir .

Системная переменная log_error может быть установлена ​​в группе опций сервера в файле опций перед запуском сервера. Например, чтобы записать журнал ошибок в файл ${hostname}.err по умолчанию , вы можете настроить следующее:

[mariadb]
...
log_error

Если вы настроите определенное имя файла в качестве системной переменной log_error и если это не абсолютный путь, то он будет относительным к каталогу datadir . Например, если вы настроили следующее, журнал ошибок будет записываться в mariadb.err в каталоге datadir :

[mariadb]
...
log_error=mariadb.err

Если это относительный путь, то log_error относится к каталогу datadir .

Однако системная переменная log_error также может быть абсолютным путем. Например:

[mariadb]
...
log_error=/var/log/mysql/mariadb.err

Другой способ настроить имя файла журнала ошибок — установить параметр log-basename , который настраивает MariaDB на использование общего префикса для всех файлов журнала (например , общий журнал запросов , журнал медленных запросов , журнал ошибок, двоичные журналы и т. д .). Имя файла журнала ошибок будет создано путем добавления расширения .err к этому префиксу. Например, если вы настроили следующее, журнал ошибок все равно будет записываться в mariadb.err в каталоге datadir :

[mariadb]
...
log-basename=mariadb
log_error

Лог-базовое имя не может быть абсолютным путем. Имя файла журнала относится к каталогу datadir .

Запись журнала ошибок в Stderr на Unix

В Unix, если системная переменная log_error не установлена, то ошибки записываются в stderr , что обычно означает, что сообщения журнала выводятся на терминал, запустивший mysqld .

Если системная переменная log_error была установлена ​​в файле опций или в командной строке, ее все равно можно отменить, указав --skip-log-error .

Запись журнала ошибок в Syslog на Unix

В Unix журнал ошибок также можно перенаправить в системный журнал . Как это будет сделано, зависит от того, как вы запускаете MariaDB.

Syslog с mysqld_safe

Если вы запускаете MariaDB с mysqld_safe , то журнал ошибок можно перенаправить в syslog. См. mysqld_safe: Настройка MariaDB для записи журнала ошибок в системный журнал для получения дополнительной информации.

Syslog с Systemd

Если вы запускаете MariaDB с помощью systemd , то журнал ошибок также может быть перенаправлен в syslog. См. Systemd: Настройка MariaDB для записи журнала ошибок в системный журнал для получения дополнительной информации.

systemd также имеет свою собственную систему журналирования, называемую journal , и вместо этого некоторые ошибки могут регистрироваться там. См. Systemd:Журнал Systemd для получения дополнительной информации.

Запись журнала ошибок в консоль на Windows

В Windows, если указана консольная опция и не используется системная переменная log_error , то ошибки записываются в консоль. Если указаны оба параметра, последний вариант имеет приоритет.

Запись журнала ошибок в программу просмотра событий Windows Event Viewer

В Windows сообщения журнала об ошибках также записываются в средство просмотра событий Windows. Вы можете найти сообщения журнала ошибок MariaDB, просмотрев журналы Windows и выбрав приложение или журнал приложений , в зависимости от версии Windows.

В MariaDB 10.3 и ранее вы можете найти сообщения журнала ошибок MariaDB, выполнив поиск по Source MySQL .

В MariaDB 10.4 и более поздних версиях вы можете найти сообщения журнала ошибок MariaDB, выполнив поиск по источнику MariaDB .

Настройка вербозиции журнала ошибок

Системная переменная log_warnings может использоваться для настройки детализации журнала ошибок. Его можно изменить динамически с помощью SET GLOBAL . Например:

SET GLOBAL log_warnings=3;

Его также можно установить либо в командной строке, либо в группе опций сервера в файле опций перед запуском сервера. Например:

[mariadb]
...
log_warnings=3

Некоторые из предупреждений,включенных в каждый уровень сложности,описаны ниже.

Системная переменная log_warnings влияет только на некоторые сообщения журнала . Некоторые сообщения журнала всегда записываются в журнал ошибок, независимо от детализации журнала ошибок. Например, log_warnings не влияет на большинство предупреждений механизма хранения InnoDB . Полный список сообщений журнала, на которые влияет log_warnings , см. в описании системной переменной log_warnings .

Уровень гербицидности 0

Если log_warnings равен 0 , то многие необязательные предупреждения не будут регистрироваться. Однако это не препятствует регистрации всех предупреждений, поскольку некоторые основные предупреждения всегда будут записываться в журнал ошибок. Например:

  • Если строгий режим InnoDB отключен, и если DDL выполняется для таблицы, которая вызывает ошибку «Размер строки слишком большой» , то InnoDB регистрирует предупреждение:
[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.

Однако, если строгий режим InnoDB включен, то это же сообщение будет зарегистрировано как ошибка.

Уровень гербицидности 1

Если log_warnings равно 1 , то регистрируются многие типы предупреждений. Некоторые полезные предупреждения:

  • Replication-related messages:
[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
  • Сообщения,связанные с ошибками DNS поиска:
[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.

Частые предупреждения о небезопасных операторах для репликации на основе операторов могут привести к тому, что журнал ошибок станет очень большим. MariaDB автоматически обнаружит частые повторяющиеся предупреждения о небезопасных операторах для репликации на основе операторов . После обнаружения 10 одинаковых предупреждений MariaDB предотвратит повторную запись того же предупреждения в журнал ошибок в течение следующих 5 минут.

Уровень гербицидности 2

Если log_warnings равно 2 , то выводится несколько других видов предупреждений. Например:

  • Сообщения,связанные с ошибками отказа в доступе:
[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.
  • Сообщения, относящиеся к файлам, используемым для сохранения состояния репликации :
    • Либо файл master.info по умолчанию , либо файл, настроенный опцией master_info_file .
    • Либо файл relay-log.info по умолчанию , либо файл, настроенный системной переменной relay_log_info_file .
[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)

Уровень гербицидности 3

Если log_warnings равно 3 , то печатается пара других различных видов предупреждений. Например:

  • Сообщения,связанные с вариантами языка старого образца:
[Warning] An old style 
  part detected: /usr/local/mysql/data/
[Warning] Use 
  • Сообщения, относящиеся к прогрессу InnoDB online DDL :
[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

Если log_warnings равно 4 , то печатается пара других различных видов предупреждений. Например:

Если log_warnings равно 9 , то выводятся очень подробные предупреждения. Например:

MariaDB не поддерживает системную переменную log_error_verbosity , добавленную в MySQL 5.7.

Формат состоит из даты (гггг-мм-дд)и времени,идентификатора потока,затем типа ошибки (Примечание,Предупреждение или Ошибка)и сообщения об ошибке,например:

До версии MariaDB 10.1.4 формат состоял только из даты (ггммдд) и времени, за которыми следовал тип ошибки (примечание, предупреждение или ошибка) и сообщение об ошибке, например:

Дистрибутивы Unix и Linux предлагают утилиту logrotate , которая упрощает ротацию файлов журналов. Дополнительную информацию о том, как использовать эту утилиту для ротации журнала ошибок, см. в разделе Ротация журналов в Unix и Linux .

Многие сообщения об ошибках готовы из файла сообщений об ошибках,который содержит локализованные сообщения об ошибках.Если сервер не может найти этот файл при запуске,то вы можете увидеть ошибки,как показано ниже:

Если эта ошибка возникает из-за того, что файл находится в пользовательском расположении, вы можете настроить это расположение, задав системную переменную lc_messages_dir либо в командной строке, либо в группе параметров сервера в файле параметров перед запуском сервера. Например:

Если вы хотите использовать другую локаль для сообщений об ошибках, вы также можете установить системную переменную lc_messages . Например:

Содержание,воспроизводимое на этом сайте,является собственностью соответствующих владельцев,и это содержание не просматривается заранее компанией MariaDB.Взгляды,информация и мнения,выраженные в этом содержании,не обязательно представляют собой взгляды,информацию и мнения,выраженные MariaDB или любой другой стороной.

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 SQL_ERROR_LOG plugin.

Configuring the Error Log Output Destination

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

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, then 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:

[mariadb]
...
log_error

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:

[mariadb]
...
log_error=mariadb.err

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. For example:

[mariadb]
...
log_error=/var/log/mysql/mariadb.err

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:

[mariadb]
...
log-basename=mariadb
log_error

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, then errors are written to stderr, which usually means that the log messages are output to the terminal that started mysqld.

If the log_error system variable was set in an option file or on the command-line, then 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 mysqld_safe

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

Syslog with Systemd

If you start MariaDB with systemd, then 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, then errors are written to the console. If both options are specified, then 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, and then selecting Application or Application Log, depending on the Windows version.

In MariaDB 10.3 and before, you can find MariaDB’s error log messages by searching for the Source MySQL.

In MariaDB 10.4 and later, you can find MariaDB’s error log messages by searching for the Source MariaDB.

Configuring the Error Log Verbosity

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:

SET GLOBAL log_warnings=3;

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:

[mariadb]
...
log_warnings=3

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, then 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, then InnoDB will log a warning:
[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.

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

Verbosity Level 1

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

  • Replication-related messages:
[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
  • Messages related to DNS lookup failures:
[Warning] IP address '192.168.1.193' could not be resolved: Name or service not known
  • Messages related to the event scheduler:
[Note] Event Scheduler: Loaded 0 events
  • Messages related to unsafe statements for statement-based replication:
[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.

Verbosity Level 2

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

  • Messages related to access denied errors:
[Warning] Access denied for user 'root'@'localhost' (using password: YES)
  • Messages related to connections that are aborted due to errors or timeouts:
[Warning] Aborted connection 35 to db: 'unconnected' user: '[email protected]' host: '192.168.1.40' (Got an error writing communication packets)
[Warning] Aborted connection 36 to db: 'unconnected' user: '[email protected]' 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)
  • Messages related to table handler errors:
[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.
  • 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.
[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'.
  • Messages about a master’s binary log dump thread:
[Note] Start binlog_dump to slave_server(263316466), pos(, 4)

Verbosity Level 3

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

  • Messages related to old-style language options:
[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.
  • Messages related to progress of InnoDB online DDL:
[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

Verbosity Level 4

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

  • Messages related to killed connections:
[Warning] Aborted connection 53 to db: 'db1' user: 'user2' host: '192.168.1.50' (KILLED)
  • Messages related to all closed connections:
[Warning] Aborted connection 56 to db: 'db1' user: 'user2' host: '192.168.1.50' (CLOSE_CONNECTION)
  • Messages related to released connections, such as when a transaction is committed and completion_type is set to RELEASE:
[Warning] Aborted connection 58 to db: 'db1' user: 'user2' host: '192.168.1.50' (RELEASE)

Verbosity Level 9

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

  • Messages about initializing plugins:
[Note] Initializing built-in plugins
[Note] Initializing plugins specified on the command line
[Note] Initializing installed plugins

MySQL’s log_error_verbosity

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

Format

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

160615 16:53:08 [Note] InnoDB: The InnoDB memory heap is disabled

From MariaDB 10.1.5, the date format has been extended to yyyy-mm-dd, and the thread ID has been added, for example:

2016-06-15 16:53:33 139651251140544 [Note] InnoDB: The InnoDB memory heap is disabled

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 ready from an error messages file that contains localized error messages. If the server can’t find this file when it starts up, then you might see errors like the following:

[ERROR] Can't find messagefile '/usr/share/errmsg.sys'

If this error is occurring because the file is in a custom location, then 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. For example:

[mariadb]
...
lc_messages_dir=/usr/share/mysql/

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

[mariadb]
...
lc_messages_dir=/usr/share/mysql/
lc_messages=en_US

See Setting the Language for Error Messages for more information.

Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.

In this MariaDB tutorial, we will learn about “MariaDB logs” which means we will learn about many log files in MariaDB like error log, slow query log, and how to deal with these log files. Additionally, we will cover the following topics.

  • MariaDB Logs
  • MariaDB Logs Windows
  • MariaDB Logs Ubuntu
  • MariaDB Logs Location
  • MariaDB Logs CentOS
  • MariaDB Logs Linux
  • MariaDB Logs docker
  • MariaDB Logs To Syslog
  • MariaDB Logs Config
MariaDB Logs

The log file contains the records of events of operating systems, software, and processes over a certain time. It keeps the record of every event that occurs within the system at a certain time. So here MariaDB has many log file that keeps records of the event like starting and stopping of server, error log related to the query, database crash log, and critical errors that occur with the database.

The MariaDB has variables that can be used to describe when to log and what to log. The MariaDB has many log files but here we will learn about the most common log files in MariaDB that this given below.

The error log: It keeps the record of the critical error that generates while performing the server operation, start and stop information, and table corruption. The destination path and file name of the error log file is configurable or we can specify the file name and destination where the error log should be written.

A variable log_error is used to set the path and file name of the error log in MariaDB. The code is given to specify the name and destination of the error log file.

SET GLOBAL log_error = path/file_name.err

Where,

  • path: It is a destination where the file will be saved.
  • file_name.err: It is the name of the file to which the error log is written.

General query log: It is a log that records every query sent to the server or query received by the server immediately and also which client is connecting to and disconnecting from a server. But general query log is not enabled by default, to enable this log set the system variable name general_log to 1. Use the below code to enable the general query log.

SET GLOBAL general_log =1

Where SET GLOBAL is the command to set the value of system variables.

To configure the path and general log filename, the general_log_file system variable is used. Use the below code to configure the path and file name.

SET GLOBAL general_log_file = 'file_name.log' -- To cofigure the file name only

SET GLOBAL general_log_file = path/file_name.log -- To configure the pathe with filename

Slow query log: The slow query log keeps the record of the queries that take a long time to execute. The slow query log is not enabled by default, to enable this log set the system variable slow_query_log to 1. Use the below code to enable a slow query log.

SET GLOBAL slow_query_log =1

Where SET GLOBAL is the command to set the value of system variables.

To configure the path and general log filename, the slow_query_log_file system variable is used. Use the below code to configure the path and file name.

SET GLOBAL slow_query_log_file = 'file_name.log' -- To cofigure the file name only

SET GLOBAL slow_query_log_file = path/file_name.log -- To configure the pathe with filename

The binary log: It is a log that keeps the records of all kinds of changes that occur in the database like time taken by query to execute, changes to data, or data structure. The query containing statements ALTER, DELETE, INSERT, UPDATE and CREATE is logged.

All these logs are saved in a binary format with binary log index files that is not readable with the regular editor. The logs are generated in three binary format row-based logging, statement-based logging and the combination of these two formats.

It is enabled by specifying the option --log-bin with command mysqld while starting the database server.

Read: MariaDB Temporary Table

MariaDB Logs Windows

The logs are saved in the data folder of MariaDB in Windows, Let’s check the file name and its location using the below code in MariaDB prompt.

SHOW VARIABLES LIKE 'log_error';

The log_error is system variables that can be viewed using the command SHOW VARIABLES LIKE.

MariaDB logs Windows
MariaDB logs Windows

From the output, we can see that the location of variable log_error is C:Program FilesMariaDB 10.6dataMSI.err by default and the name of the log file is MSI.err

Open the log file MSI.err with text editor notepad.

Maria logs Windows file
Maria logs Windows file

From the output, we can see that each event that occurs in the database has been recorded in the log file with date, time, database engine, and the description of events.

Let’s view the next log that is General query log and enable this log using the below code.

SHOW VARIABLES LIKE 'general_log';
MariaDB logs Windows general query log
MariaDB logs Windows general query log

As we can see that the general_log value is OFF which means the log is not enabled by default, so we need to enable this log using the below code.

SET GLOBAL general_log =1;
SHOW VARIABLES LIKE 'general_log';

After running the above code the general query log gets enabled. The output of the above code is given below.

MariaDB logs Windows general query log enabled
MariaDB logs Windows general query log enabled

Now the variable general_log value is ON which means it is enabled. By default, the general log file is saved in a folder data of MariaDB as {host_name}.log. This file name and path can be configured using the system variable general_log_file.

Let’s change the name of the general log file using the below code.

SET GLOBAL general_log_file = 'mariadbtips.log';

SHOW VARIABLES LIKE 'general_log_file';
MariaDB logs Windows general query log filename
MariaDB logs Windows general query log filename

The above output shows that the name of general_log the file is mariadbtip.log that is configured using the system variable general_log_file.

Also, change the file path using the below command.

SET GLOBAL general_log_file = 'C:/Users/Mariadbtips/mariadbtips.log';
SHOW VARIABLES LIKE 'general_log_file';
MariaDB logs Windows general query log path
MariaDB logs Windows general query log path

From the output, we can see that the location of variable general_log is C:/Users/Mariadbtips/mariadbtips.log and the name of the log file is mariadbtips.log.

As we know that the general query log records each SQL query sent to the server, so run any query or the below query and open the log file mariadbtips.log by going to the location where it is saved.

SHOW VARIABLES LIKE 'general_log';

As we run the above query, this query get logged into the file mariadbtips.log. Let’s open this file and check the query above query.

MariaDB logs Windows general query log mariadbtips
MariaDB logs Windows general query log mariadbtips

The general log file mariadbtips.log contains the query that we issued to the server, the log file recorded the date, time, and the query that we run on the server as we can see in the log file.

Now we have another log that is Slow query log which keeps a record of the queries that take a long time to execute. Enable this query using the below steps because it was disabled by default.

Login into the MariaDB database using the below code.

mysql -u root -p

Enable the slow query log using the below code.

SET GLOBAL slow_query_log = 1;

Exit from the session or MariaDB database.

exit

Run the above code and log out from the MariaDB session or prompt and then log in again to see the changes.

mysql -u root -p

Check the variable whether it is enabled or not.

SHOW VARIABLES LIKE 'slow_query_log';
MariaDB logs Windows slow query log
MariaDB logs Windows slow query log

Now slow_query_log value is ON which means it is enabled now. we can configure the slow query log file name and location where it will be saved using the system variable name slow_query_log_file.

Let’s change the slow query filename and location using the below code.

SET GLOBAL slow_query_log_file = 'C:/Users/Mariadbtips/mariadbslowquery.log'

View the filename and path using the below code.

 SHOW VARIABLES LIKE 'slow_query_log_file';

The output of the code is given below.

MariaDB logs Windows slow query log filename and path
MariaDB logs Windows slow query log filename and path

From the output, we can see that the location of variable slow_query_log is C:/Users/Mariadbtips/mariadbslowquery.log and the name of the log file is mariadbslowquery.log.

This is the last most common log is Binary Log that keeps the record of all kinds of changes made to the database as well as data or data structure and time taken by each query. The system variable that can be used to enable this log is sql_log_bin for the current session but enabled by default. Use the below steps to enable this log file.

Login into the MariaDB database using the below code.

mysql -u root -p

Enable the slow query log using the below code.

SET sql_log_bin =1

Before running above, remember that the log is enabled for the current session by default.

Check the variable whether it is enabled or not.

SHOW VARIABLES LIKE 'log_bin';
MariaDB logs Windows binary log
MariaDB logs Windows binary log

Read: MariaDB Reset Root Password

MariaDB Logs Ubuntu

In MariaDB, we don’t need to enable the error log because it is enabled by default. So here in this section, we will change the error log file and path using the system variable log_error.

Log into MariaDB prompt and type the below code.

mysql -u root -p

Run the below query to check the status of system variable log_error.

SHOW VARIABLES LIKE 'log_error';
MariaDB Logs Ubuntu error log status
MariaDB Logs Ubuntu error log status

From the output, we can see that the location and name of the error log file using the system variable log_error is null by default.

Configure the error log file by making changes to the MariaDB configuration file. Go to folder /etc/mysql/mariadb.conf.d/50-server.cnf and open the file 50-server.cnf using any editor.

Find this line log_error = /var/log/mysql/error.log in a file 50-server.cnf and remove the symbol # from the front of the line or uncomment it.

Here /var/log/mysql/error.log is default directory to store the error log file, we can change this path according to our need.

MariaDB Logs Ubuntu error log configuration file
MariaDB Logs Ubuntu error log configuration file

To apply this new setting to the configuration file, restart the MariaDB server using the below code.

sudo systemctl restart mariadb

Let’s view this error.log file using any editor like gedit in Ubuntu that is stored at the location /var/log/mysql/error.log.

sudo gedit /var/log/mysql/error.log
MariaDB Logs Ubuntu view error log
MariaDB Logs Ubuntu view error log

Enable the general log query of MariaDB in Ubuntu by assigning value 1 to the system variable general_log. Use the below code to enable the log file.

SET GLOBAL gneral_log =1;

Check the status of the variable using the below code.

SHOW VARIABLES LIKE 'general_log';
MariaDB Logs Ubuntu general query log status
MariaDB Logs Ubuntu general query log status

The general query log is enabled now, let’s configure the general query log filename and path using the system variable general_log_file.

View the default location and filename of the general query log file using the system variable general_log_file using the below code.

SHOW VARIABLES LIKE 'general_log_file';
MariaDB Logs Ubuntu general query log file status
MariaDB Logs Ubuntu general query log file status

From the output, we can see that the location of variable general_log is /var/lib/mysql/ubuntu.log by default and the name of the log file is ubuntu.log.

Change the path and filename of the general log file using the below code.

SET GLOBAL general_log_file = '/var/lib/mysql/mariadb.log';

Check the changed path and filename using the below code.

SHOW VARIABLES LIKE 'general_log_file';

Let’s run any query on MariaDB because the general query log file records every SQL query sent to the MariaDB server.

use mysql;
SELECT * FROM user;
MariaDB Logs Ubuntu general query log file
MariaDB Logs Ubuntu general query log file

Open the genera log file by going to a location /var/lib/mysql/mariadb.log where it is saved in Ubuntu, use the below code to open the mariadb.log file.

MariaDB Logs Ubuntu general query log
MariaDB Logs Ubuntu general query log

Let’s enable the next log which is the slow query log file using the below steps.

Enable the slow query log of MariaDB in Ubuntu by assigning value 1 to the system variable slow_query_log. Use the below code to enable the log file.

SET GLOBAL slow_query_log =1;
exit

After running the above code exit from the MariaDB session and log in again to check the status of the variable using the below code.

MariaDB Logs Ubuntu slow query log status
MariaDB Logs Ubuntu slow query log status
SHOW VARIABLES LIKE 'slow_query_log';
MariaDB Logs Ubuntu slow query log status on
MariaDB Logs Ubuntu slow query log status on

From the output, we have enabled the slow query log. We can change the filename and path of the slow query log file using the system variable slow_query_log_file. But first, check the default filename and path of the slow query log file using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file`;
MariaDB Logs Ubuntu slow query log file status
MariaDB Logs Ubuntu slow query log file status

From the output, we can see that the location of the slow query log file using the system variable slow_query_log is /var/lib/mysql/ubuntu-slow.log by default and the name of the log file is ubuntu-slow.log.

Change the path and filename of the slow query log file using the below code.

SET GLOBAL slow_query_log_file = '/var/lib/mysql/mariadb-slow.log';

Check the changed path and filename using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file';
MariaDB Logs Ubuntu slow query log file checking status
MariaDB Logs Ubuntu slow query log file checking status

We have successfully changed the filename and path of the slow query log file, now we can go to that location and open the file to check that which query has taken a long time to execute.

At last, we will learn about the log Binary Log which records all kinds of changes made to the database.

First, check whether it is ON or OFF using the below code into the MariaDB prompt.

SHOW VARIABLES LIKE 'log_bin';
exit

To enable this log file, configure the error log file by making changes to the MariaDB configuration file. Go to the folder /etc/mysql/mariadb.conf.d/50-server.cnf and open the file 50-server.cnf using any editor.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Find lines that start with (log_bin, expire_logs_days, max_binlog_size) in a file 50-server.cnf and remove the symbol # from the front of these lines.

Here in the below code /var/log/mysql/error.log is the default directory to store the binary log file, we can change this path according to our need.

log_bin                = /var/log/mysql/mysql-bin.log
expire_logs_days        = 10
max_binlog_size        = 100M
MariaDB Logs Ubuntu enable binary log
MariaDB Logs Ubuntu enable binary log

To apply this new setting to the configuration file, restart the MariaDB server using the below code.

sudo systemctl restart mariadb
MariaDB Logs Ubuntu enable binary log status
MariaDB Logs Ubuntu enable binary log status

After enabling the binary log, a new file is created with the name mysql-bin.000001 in the directory /var/log/mysql. So here we cannot view this file with a normal text editor because it is a binary format file.

Read: MariaDB Backup Database

MariaDB Logs Location

The log files reside in a different location based on a different platform or operating system, and we can configure the location of the logs file on each operating system according to our need.

So here we will cover the two operating systems Windows and Ubuntu(Linux).

On Windows by default, all log files are saved in the data folder of MariaDB which is C:Program FilesMariaDB 10.6data, this location is configurable using the system variable of that log files.

On Ubuntu (Linux) by default, all log files reside at the location /var/lib/mysql in MariaDB, In Linux MariaDB all files reside in folder name is mysql, because MariaDB is forked from MYSQL.

Read: MariaDB Enable Remote Access

MariaDB Logs CentOS

So here in this section, we will look at the logs file of MariaDB in CentOS, CentOS is also a Linux distribution-based operating system.

First, we will look the the Error log file in MariaDB which is enabled by default as we know, so login into MariaDB prompt on CentOS using the below code and check the filename and location of the log file.

mysql -u root -p

Check the filename and location of the log file using the system variable log_error. This system variable is also used to set the filename and path of the log file.

SHOW VARIABLES LIKE 'log_error';
MariaDB Logs CentOS error log file status
MariaDB Logs CentOS error log file status

From the output, we can see that the location of the error log file using the system variable log_error is /var/log/mariadb/mariadb.log by default and the name of the log file is mariadb.log.

Now, we can open the log file mariadb.log by going to that location using the below code.

sudo nano /var/log/mariadb/mariadb.log

The next log file that we will look at General Query Log , which records each query sent to the MariaDB server. Let’s enable the general query log in MariaDB using the system variable general_log by following the below steps.

Check the status of the general query log whether it ON or OFF but is disabled by default.

SHOW VARIABLES LIEK 'general_log';

Then enable the general query log using the below code, if it is not enabled.

SET GLOBAL general_log =1;

Again the status of the general query log file using the below code.

SHOW VARIABLES LIKE 'general_log';
MariaDB Logs CentOS general query log enable
MariaDB Logs CentOS general query log enable

Let’s view the filename and path of the general query log using the system variable general_log_file.

SHOW VARIABLES LIEK 'general_log_file';
MariaDB Logs CentOS general query log file location
MariaDB Logs CentOS general query log file location

From the output, we can see that the location of the general query log file using the system variable general_log_file is /var/lib/mysql/localhost.log by default and the name of the log file is localhost.log.

We can open the file localhost.log by going to that location and seeing logs related to the general query log using the below code.

sudo nano /var/lib/mysql/localhost.log

Next log is Slow Query Log the file that keeps a record of SQL queries that take a long time to execute.

Enable the slow query log of MariaDB in CentOS by assigning value 1 to the system variable slow_query_log. Use the below code to enable the log file.

SET GLOBAL slow_query_log =1;
exit

After running the above code exit from the MariaDB session and log in again to check the status of the variable using the below code.

MariaDB Logs CentOS slow query log enable
MariaDB Logs CentOS slow query log enable
SHOW VARIABLES LIKE 'slow_query_log`;
MariaDB Logs CentOS slow query log enable status
MariaDB Logs CentOS slow query log enable status

From the output, we have enabled the slow query log. We can change the filename and path of the slow query log file using the system variable slow_query_log_file. But first, check the default filename and path of the slow query log file using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file`;
MariaDB Logs CentOS slow query log file location and filename
MariaDB Logs CentOS slow query log file location and filename

From the output, we can see that the location of the slow query log file using the system variable slow_query_log is /var/lib/mysql/localhost-slow.log by default and the name of the log file is localhost-slow.log.

Change the path and filename of the slow query log file using the below code.

SET GLOBAL slow_query_log_file = '/var/lib/mysql/mariadbtips-slow.log';

Check the changed path and filename using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file';

MariaDB Logs CentOS slow query log file location and filename status

MariaDB Logs CentOS slow query log file location and filename status

We have successfully changed the filename and path of the slow query log file, now we can go to that location /var/lib/mysql/mariadbtips-slow.log and open the file to check that which query has taken a long time to execute.

At last, we will learn about the log Binary Log which records all kinds of changes made to the database.

First, check whether it is ON or OFF using the below code into the MariaDB prompt.

SHOW VARIABLES LIKE 'log_bin';
exit
MariaDB Logs CentOS status binary log
MariaDB Logs CentOS status binary log

From the output, we can see that the binary log is OFF.

To enable this log file, configure the error log file by making changes to the MariaDB configuration file. Go to the folder /etc/my.cnf.d/mariadb-server.cnf and open the file mariadb-server.cnf using any editor.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Add the following lines as shown in the below output.

log-bin=/var/log/mariadb/lob-bin.01

Here in the above code /var/log/mariadb/lob-bin.01 is the default directory to store the binary log lob-bin.01 file, we can change this path according to our need.

MariaDB Logs CentOS enable binary log
MariaDB Logs CentOS enable binary log

To apply this new setting to the configuration file, restart the MariaDB server using the below code.

sudo systemctl restart mariadb
MariaDB Logs CentOS enable binary log status
MariaDB Logs CentOS enable binary log status

After enabling the binary log, a new file is created with the name lob-bin.01 in the directory /var/log/mariadb. So here we cannot view this file with a normal text editor because it is a binary format file.

Read: MariaDB Truncate Table

MariaDB Logs Config

In MariaDB, we can configure the logs filename and the using the different system variables relate to that log file.

So here in this section, we will cover the steps to configure the most common log files in MariaDB that we have learned in the above sub-section of this tutorial. Whatever the operating systems you are using, the step is the same but the location of the log file can be different.

Before configuring the logs in MariaDB, make sure that the log file is enabled that we are going to use. If you don’t know how to enable then follow the above sub-topics according to your operating system.

To configure Error log, the system variable log_error is used to configure this kind of log file. If we need to change the filename then run the command given below.

SET GLOBAL log_error = 'mariadbtips.err';

Or if we want to change the path of the log file used the below code.

SET GLOBAL log_error = 'path/filename.err';

Where,

  • path: It is a destination where the file will be saved.
  • file_name.err: It is the name of the file to which the error log is written.

To configure General query log the system variable general_log_file is used to configure this kind of log file. If we need to change the filename then run the command given below.

SET GLOBAL general_log_file = 'mariadbtips.log';

Or if we want to change the path of the log file used the below code.

SET GLOBAL general_log_file = 'path/filename.log';

Where,

  • path: It is a destination where the file will be saved.
  • file_name.log: It is the name of the file to which the error log is written.

To configure Slow Query Log the system variable slow_query_log_file is used to configure this kind of log file. If we need to change the filename then run the command given below.

SET GLOBAL slow_query_log_file = 'mariadbtips-slow.log';

Or if we want to change the path of the log file used the below code.

SET GLOBAL slow_query_log_file = 'path/filename-slow.log';

Where,

  • path: It is a destination where the file will be saved.
  • file_name-slow.log: It is the name of the file to which the error log is written.

Read: MariaDB Rename Column

MariaDB Logs docker

So, here in this section, we will look at the logs file of MariaDB running in Docker.

First, we will look at the Error log file in MariaDB which is enabled by default as we know, so login into the MariaDB prompt by clicking on the button CLI of container MariaDB in Docker and use the below code and check the filename and location of the log file.

mysql -u root -p

Check the filename and location of the log file using the system variable log_error. This system variable is also used to set the filename and path of the log file.

SHOW VARIABLES LIKE 'log_error';

From the output, we can see that the location and name of the error log file using the system variable log_error is null by default.

Configure the error log file by making changes to the MariaDB configuration file.

Now, we can open the log file hostname.log by going to that location using the below code.

sudo nano /var/log/mariadb/mariadb.log

The next log file that we will look at General Query Log , which records each query sent to the MariaDB server. Let’s enable the general query log in MariaDB using the system variable general_log by following the below steps.

Check the status of the general query log whether it ON or OFF but is disabled by default.

SHOW VARIABLES LIEK 'general_log';

Then enable the general query log using the below code, if it is not enabled.

SET GLOBAL general_log =1;

Again the status of the general query log file using the below code.

SHOW VARIABLES LIKE 'general_log';
MariaDB Logs Docker general query log enable
MariaDB Logs Docker general query log enable

Let’s view the filename and path of the general query log using the system variable general_log_file.

SHOW VARIABLES LIEK 'general_log_file';
MariaDB Logs Docker general query log file location
MariaDB Logs Docker general query log file location

From the output, we can see that the location of the general query log file using the system variable general_log_file is /var/lib/mysql/41d2cef2a4c0.log by default and the name of the log file is 41d2cef2a4c0.log.

We can open the file 41d2cef2a4c0.log by going to that location and seeing logs related to the general query log using the below code.

sudo nano /var/lib/mysql/41d2cef2a4c0.log

Next log is Slow Query Log the file that keeps a record of SQL queries that take a long time to execute.

Enable the slow query log of MariaDB in Docker by assigning value 1 to the system variable slow_query_log. Use the below code to enable the log file.

SET GLOBAL slow_query_log =1;

exit

After running the above code exit from the MariaDB session and log in again to check the status of the variable using the below code.

mysql -u root -p

SHOW VARIABLES LIKE 'slow_query_log`;
MariaDB Logs Docker slow query log enable status
MariaDB Logs Docker slow query log enable status

From the output, we have enabled the slow query log. We can change the filename and path of the slow query log file using the system variable slow_query_log_file. But first, check the default filename and path of the slow query log file using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file`;
MariaDB Logs Docker slow query log file location and filename
MariaDB Logs Docker slow query log file location and filename

From the output, we can see that the location of the slow query log file using the system variable slow_query_log is /var/lib/mysql/41d2cef2a4c0-slow.log by default and the name of the log file is 41d2cef2a4c0-slow.log

Change the path and filename of the slow query log file using the below code.

SET GLOBAL slow_query_log_file = '/var/lib/mysql/41d2cef2a4c0-slow.log';

Check the changed path and filename using the below code.

SHOW VARIABLES LIKE 'slow_query_log_file';
MariaDB Logs Docker slow query log file location and filename status
MariaDB Logs Docker slow query log file location and filename status

We have successfully changed the filename and path of the slow query log file, now we can go to that location /var/lib/mysql/41d2cef2a4c0-slow.log and open the file to check that which query has taken a long time to execute.

Read: MariaDB Transaction

MariaDB Logs Linux

The steps to enable, configure and view the log files of MariaDB is the same for all Linux based systems, refer to above sub-section MariaDB Logs Ubuntu and MariaDB Logs CentOS depending on what Linux distribution you are using.

Read: MariaDB Rename Index

MariaDB Logs To Syslog

The Syslog is called System Logging Protocol that is used on different devices like Windows Servers, Linux Servers, Routers, etc. It keeps the log or event information on these devices and sends it to the Syslog Server which is also called a collector.

In MariaDB, by default the Error Log is redirected to Syslog, the redirection of the error log to Syslog depends upon the way the MariaDB server starts.

We can start the MariaDB server with two ways to redirect the error log to Syslog.

  • Start with mysqld_safe.
  • Start with systemd.

You may also like to read the following MariaDB tutorials.

  • MariaDB Order By Clause
  • MariaDB Drop Table
  • MariaDB Union Operator
  • MariaDB Select Statement
  • MariaDB Set Variable
  • MariaDB If Null + Examples
  • MariaDB Variables Tutorial

So, in this tutorial, we have learned about the “MariaDB Logs” and covered the following topics.

  • MariaDB Logs
  • MariaDB Logs Windows
  • MariaDB Logs Ubuntu
  • MariaDB Logs Location
  • MariaDB Logs CentOS
  • MariaDB Logs Linux
  • MariaDB Logs docker
  • MariaDB Logs To Syslog
  • MariaDB Logs Config

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Last updated on:  2021-07-12

Authored by:  Alfonso Murillo


MariaDB® logs include the following types:

  • Error log: This log is always enabled, logging all critical errors.
    It can also log warnings.

  • General query log: The --general-log variable enables this log. You
    can debug and audit queries by enabling it.

  • Slow query log: Enable this log by starting mysqld with option
    --slow-query-log. You can identify queries that cause performance
    issues by enabling this log.

  • Binary log: Enable this log by starting mysqld with option --log-bin.
    This log is for replication masters only.

You can customize the log configuration of MariaDB by using system variables.

The error log

You can find error logs in the datadir directory. By default, the system names
the error logs as ${hostname}.err. The log_error system variable changes the
default name and writes logs to the datadir directory.

You can change the absolute path of the error logs by adding the path to the name,
as shown in the following example:

[mariadb]
...
log_error=/var/log/mysql/mariadb.err

You can configure the prefix of the log files with the log-basename variable.
The prefix applies to all log files, such as error logs, general query logs, slow
query logs, binary logs, and so on. Error logs have the .err extension.

Send error logs to stderr

In Unix® and Unix-like environments, you don’t set the log_error variable,
and stderr (the terminal window where you ran mysqld) displays errors by
default. If stderr doesn’t display errors, unset the log_error variable
with the --skip-log-error option.

Error log verbosity

Use the log_warnings system variable to configure the verbosity of error logs:

[mariadb]
...
log_warnings=3

The warnings can have the following verbosity levels:

  • Level 0 logs some core warnings but ignores many optional warnings.

  • Level 1 logs the following warnings, among others:

    • Replication-related messages.
    • DNS-lookup failure messages.
    • Event scheduler messages.
    • Unsafe statements for statement-based replication messages.
  • Level 2 logs the following warnings, among others:

    • Access-denied errors.
    • Aborted connections due to timeouts.
    • Table-handler errors.
  • Level 3 logs the following warnings, among others:

    • Old-style language options messages.
    • Progress of InnoDB online DDL-related messages.
  • Level 4 logs the following warnings, among others:

    • Killed connections messages.
    • All closed connections messages.
    • Released connections messages.
  • Level 9 logs the following warning, among others:

    • Initializing plugins messages.

Refer to the MariaDB documentation for more information about
system variables configuration
and error logs.

Use the Feedback tab to make any comments or ask questions. You can also start a conversation with us.

MariaDB Logs

Definition of MariaDB Logs

MariaDB server uses a different log file such as error log file, binary log file, general query log, and slow query log files. As per our requirement, we can change the status of log files that enable and disable log files. The main purpose of a log file is that to store different data during the different operation, for example, if we consider error log file, the error log file is used to store the critical error occurred during the MariaDB server operation, table corruption and start and stop information. If we consider SQL errors it can also be used in different log files by using the SQL_ERROR plugin.

Syntax:

set global log type = value;

Explanation:

In the above syntax, we use the set global command, here log type means log file name and value means 1 or 0 that we need to set.

show global variables like 'log file name';

Explanation:

In the above example, we use show global variable command to see the log file, here we use log file name means you can use any log file name to see the details of a specified log file.

How Logs works in MariaDB?

Now let’s see how logs work in MariaDB as follows. Basically, MariaDB uses different log files let’s see one by one.

1. Error Log

In this log file, it contains all records of critical errors that occurred during the different operations of the server like a corrupted table, which service start and stop information. SQL error is also used in a separate log file using the SQL_ERROR_LOG plugin.

Now let’s see how we can write error logs to a file.

When we need to configure an error log to write a log file at that time we must need to set the log_error system variable. By using a system variable we can configure a specific file name, if we don’t use specified file name to the configuration at that time log will be written to hostname.err file in the directory and this is by default directory.

We can set the log_error system variable by using the server option group. For example to write error log in by default log file that is ${hostname}.err. We need to configure the following line as follows.

[mariadb]
……
log_error

If we need to configure a specific file name as a log_error system variable and this file doesn’t have an absolute path then it uses a relative path to the datadir directory. Now see the following example of a configured error log that would be written to the mariadb.err file from datadir directory.

[mariadb]
……
log_error = mariadb.err

See in above example path is a relative path but some it also uses absolute path. For example:

[mariadb]
……
log_error = C:Program Files (x86)MariaDB 10.5includemysqlmariadb.err.

We can also use another path to configure the error log file that is to set log – basename option which is configured by MariaDB.

2. General Query Log

The general query log file is used to store all details about every SQL query received from the client-side as well as all connected and disconnected client information.

Now see how we can enable the general query log as follows.

The general query log is to be disabled by default. To enable the general log file then we need to set the general_log system variable to 1 and it also changes dynamically.

For Example: 

set global general_log = 1;

We can also set general_log file by using the server option group. For example:

[mariadb]
………..
general_log

Now see how we can configure the general query log file name as follows.

For configuration purposes, we use a default data-dir directory that is ${hostname}.log and a general_log_file system variable can be changed dynamically. For example:

set global general_log_file = 'mariadb.log';

We can also set the general_log_file by using the server option group from the file option. for example:

[mariadb]
……………..
general_log
general_log_file = mariadb.log

In the above example, we use a relative path but it also uses an absolute path.

Let’s see how we select the destination file for the general query log as follows.

It can be written to a file on disk or it can be written on the general_log table in the MySQL database. For selecting the destination file for output we use log_output system variable.

set global log_output = 'specified file name';

3. Slow Query Log

In this type of log file, the slow query log file is used to store records of SQL queries that take a long time to execute. In this type of query, the password then slow query log also contains the password.

Now let’s see how we can enable the slow query log as follows.

To enable the slow query log file we use the slow_query_log system variable that means we set the global variable is 1 as follows.

set global slow_query_log = 1

We can also set it by using the server option group from the file option.

Configuration of the slow query log by using the file name as follows.

We can configure the slow query log by using a filename that means we need to set a slow_query_log_file system variable by using the relative path as well as an absolute path, same like the above-mentioned types.

4. Binary Log

In this type, we stored all records of the database and structure as well as how each query takes a long time to execute.

Examples

Let’s see the different examples of MariaDB log as follows.

Suppose we need to show log error at that time we use the following statement.

show global variables like 'log_error';

Explanation:

In the above example, we use the show variable command to show log error. The final output of the show databases queries we illustrate by using the following snapshot.

MariaDB Logs 1

Now how we can set the global general log by using the following statement.

set global general_log = 1;

Explanation:

The final output of the show databases queries we illustrate by using the following snapshot.

MariaDB Logs 2

In this way, we can set all log types as per requirement.

Conclusion

We hope from this article you have understood about the MariaDB Logs. From this article, we have learned the basic syntax of MariaDB Logs and we also see different examples of MariaDB Logs. From this article, we learned how and when we use MariaDB Logs.

Recommended Articles

We hope that this EDUCBA information on “MariaDB Logs” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. MariaDB Grant All Privileges
  2. MariaDB MaxScale
  3. MariaDB Foreign Key
  4. MariaDB Commands

I am using new relic to monitor the performance of my server. Recently I noticed a very strange problem where for every 3 hours, the server will be down for 1 minute. And in the new relic report, during the server down time, there were sudden spike on the database.

The problem is I am new in system admin, I don’t know how to view the database log. I am using Mariadb on a Ubuntu 14.04 machine. So, where can I find the log?
I tried to view in /var/log/mysql.err, /var/log/mysql.log and /var/log/mysql/error.log there are no content inside.

I also tried grep ‘mysql’ /var/log/syslog, nothing found as well.

Do I need to enable the logging in mariadb config file? If so, how?

asked Nov 21, 2015 at 20:23

dev-jim's user avatar

One of the ways to find out your current log file path is using the following SQL query:

show global variables like 'log_error';

The output should look something like this:

+---------------+---------------------+
| Variable_name | Value               |
+---------------+---------------------+
| log_error     | /var/log/mysqld.log |
+---------------+---------------------+

answered Nov 21, 2015 at 21:18

Tubeless's user avatar

TubelessTubeless

1,63014 silver badges15 bronze badges

2

On systemd linuxes (Ubuntu), it’s centralized under systemd which collects and manages kernel and user-land process logs under the journal. To view mariadb journal, run:

# journalctl -u mariadb -f

You should see something along the lines of:

-- Logs begin at Mon 2021-08-30 08:59:29 CDT. --
Aug 25 21:10:22 aorus-15g-yb mysqld[1123]: 2022-08-25 21:10:22 0 [Note] /usr/sbin/mysqld (mysqld 10.3.34-MariaDB-0ubuntu0.20.04.1) starting as process 1123 ...
Aug 25 21:10:22 aorus-15g-yb systemd[1]: Started MariaDB 10.3.34 database server.
Aug 25 21:10:22 aorus-15g-yb /etc/mysql/debian-start[1254]: Looking for 'mysql' as: /usr/bin/mysql
Aug 25 21:10:22 aorus-15g-yb /etc/mysql/debian-start[1254]: Looking for 'mysqlcheck' as: /usr/bin/mysqlcheck
Aug 25 21:10:22 aorus-15g-yb /etc/mysql/debian-start[1254]: This installation of MariaDB is already upgraded to 10.3.34-MariaDB.

answered Aug 27, 2022 at 13:36

Slawomir's user avatar

SlawomirSlawomir

1771 silver badge7 bronze badges

I had the same issue on Debian 8.5, using MariaDB 10.1.16.
I put the configuration as recommended but nothing, there was no way that the error.log file was written with the errors.

At the end, look in / var / log / syslog and there were the errors and warnings

tail -f /var/log/syslog | grep mysql

answered Dec 26, 2017 at 22:26

SergioMC's user avatar

1

On Fedora 35, it is located at /var/log/mariadb/mariadb.log. Perhaps for other recent Fedora versions or other distros as well.

answered May 4, 2022 at 6:58

MAChitgarha's user avatar

Понравилась статья? Поделить с друзьями:
  • Marantz ошибка check pow5
  • Mapsource ошибка при установке
  • Maps me ошибка загрузки карты
  • Mapmem cpp ошибка wow
  • Mapinfo ошибка при запуске