Logging in mysql linux

Журналы (logs) в MySQL

В MySQL на данный момент существуют 4 вида журнала (лога) и при достаточно серьёзной работе с базами на MySQL необходимо за ними следить. Например, бинарный лог у нас за сутки набирает около гигабайта, а размер жёсткого диска на сервере ограничен и за ними надо следить. Однако следить следует не только за бинарным логом, так как логи (журналы) в MySQL могут принести немалую пользу.

Итак, какие логи ведёт MySQL? Это:
1. бинарный лог (binary log)
2. лог ошибок (error log)
3. лог медленный запросов (slow query log)
4. лог запросов (general query log)
5. лог репликаций (relay log)

Каждый из них по-своему полезен.

Бинарный лог

В первую очередь полезен с точки зрения репликаций. Можно его бэкапить, можно использовать для восстановления данных на более точное время при использовании бэкапов. Лог содержит все команды изменений базы данных, выборки (select, show) не сохраняет, для таблиц, поддерживающих транзакции (BDB, InnoDB) запись в лог выполняется только после выполнения команды COMMIT . Для лога можно указывать список баз данных, которые надо логировать и список баз данных, которые не надо логировать. В более ранних версиях вместо бинарного лога использовался лог обновлений. Использование бинарного лога снижает производительность базы данных, однако его польза настолько велика, что крайне не рекомендуется его отключать. Рекомендуется защищать бинарный лог паролем, так как он может данные также о паролях пользователей. При достижении максимально разрешённого размера (1 гиг по умолчанию) создаётся следующий файл. Каждый новый файл имеет порядковый номер после имени.

Содержание бинарного лога можно посмотреть с помощью утилиты mysqlbinlog.

Основные настройки в my.cnf

Местоположение лога:
log_bin = /var/log/mysql/mysql-bin.log

Максимальный размер, минимум 4096 байт, по умолчанию 1073741824 байт (1 гигабайт):
max_binlog_size= 500M

Сколько дней хранится:
expire_logs_days = 3

Наиболее часто использующиеся команды

Повторение действий после операции восстановления:
shell> mysqlbinlog log_file | mysql -h server_name

Удаление логов до определённого файла:
PURGE BINARY LOGS TO ‘mysql-bin.000’;

Удаление логов до определённой даты:
PURGE BINARY LOGS BEFORE ‘YYYY-MM-DD hh:mm:ss’;

Лог ошибок

Особенно полезен в случаях сбоев. Лог содержит информацию об остановках, запусках сервера, а также сообщения о критических ошибках. Может содержать сообщения с предупреждениями (warnings).

Основные настройки в my.cnf

Местоположение лога:
log_error = /var/log/mysql/mysql.err

Флаг, указывающий стоит ли записывать в лог в том числе предупреждения (записываются, если значение больше нуля):
log_warnings = 1

Наиболее часто использующиеся команды

Переход к новому файл лога:
shell> mysqladmin flush-logs

Копирование старой части лога (необходимо, так как в случае повторного выполнения fluch он будет удалён):
shell> mv host_name.err-old backup-directory

Лог медленных запросов

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

Основные настройки в my.cnf

Местоположение лога:
log_slow_queries = /var/log/mysql/mysql_slow.log

Со скольки секунд выполнения запрос считается медленным, минимальное значений — 1 секунда, по умолчанию 10 секунд:
long_query_time = 10

Если надо логировать запросы, которые не используют индексы, надо добавить строку:
log-queries-not-using-indexes

Если надо вести лог медленных команд, таких как OPTIMIZE TABLE , ANALYZE TABLE и ALTER TABLE :
log-slow-admin-statements

Лог запросов

Лог содержит информацию о подключениях и отключениях клиентов, а также все SQL запросы, которые были получены. Фактически, это временный лог. Обычно лог удаляется автоматически сразу после выполнения всех команд (т.е. как только он стал ненужным). Лог ведётся в соответствии с очередность поступления запросов. Этот лог содержит все запросы к базе данных (независимо от приложений и пользователей). Так что если есть желание (или необходимость) проанализировать, какие необходимы индексы, какие запросы могли бы оптимизированы, то этот лог как раз может помочь в таких целях. Лог полезен не только для случаев, когда необходимо знать, какие запросы выполняются с базой данных, но и в случаях, когда ясно, что возникла ошибка с базой данных, но неизвестно, какой запрос был отправлен к базе данных (например, в случае генерации динамического SQL-а). Рекомендуется защищать лог запросов паролем, так как он может данные также о паролях пользователей.

Читайте также:  Aerocool вы cube windows
Основные настройки в my.cnf

Местоположение лога:
log = /var/log/mysql/mysql.log

Наиболее часто использующиеся команды

В отличии от других логов, перезагрузка сервера и команда fluch не инициирует создание нового лога. Но это можно сделать вручную:
shell> mv host_name.log host_name-old.log
shell> mysqladmin flush-logs
shell> mv host_name-old.log backup-directory

Лог репликаций

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

Основные настройки в my.cnf

Местоположение лога:
relay-log = /var/log/mysql/mysql-relay-bin.log

Максимальный размер:
max_relay_log_size = 500М

Наиболее часто использующиеся команды

Начать новый файл лога можно только при остановленном дополнительном (slave) сервере:
shell> cat new_relay_log_name.index >> old_relay_log_name.index
shell> mv old_relay_log_name.index new_relay_log_name.index

Команда fluch logs инициирует ротацию лога.

Источник

MySQL Log File Location

Logs are valuable. Logs generated by a major backend resource that provides clients with access to crucial data are more than just valuable; knowing where they are and being able to manage and understand the information that they contain can mean the difference between smooth, secure operation and degraded performance or even catastrophic failure for your application.

MySQL Server produces a handful of basic logs. We’ll look at which ones are important (and why), where they are, and what you can do to get the most out of them.

MySQL Logs

The three most important logs in terms of day-to-day IT operations are the error log, the slow query log, and (to a lesser degree) the general query log. Their default format is text, and they are useful for detecting and diagnosing functional problems and security issues, for improving performance, and for tracing the history of server operations and client access to the server.

The binary, relay, and DDL logs are all binary in format, and they are designed for use primarily by MySQL itself, specifically for tasks such as server replication and data recovery.

The Question of How and Where with MySQL Log Files

First, let’s take a quick look at how and under what circumstances the various MySQL distributions set default log file locations.

There are three basic types of MySQL distribution: Windows, platform-specific UNIX/Linux, and generic UNIX/Linux. In general, the platform-specific distributions have default settings for placing and enabling logs, while the generic UNIX/Linux distributions assume that logs will be managed via manual settings.

Windows

Official MySQL Windows distributions use an MSI installer with user-selectable options at various stages of the installation. The Logging Options page displays the log enabling and location defaults and also allows you to make adjustments as required.

The error, slow query, and binary logs are enabled by default, but the general query log is not enabled. The default location for each of the logs is the MySQL Data directory (C:\ProgramData\MySQL\MySQL Server [version number]\Data\), and the default log names are based on the computer’s device name.

Читайте также:  Windows 10 не открывается jpg ошибка файловой системы

You can manually enable/disable the general query, slow query, and binary logs via the installer GUI, but not the error log. You can also manually set the names and paths for each of the logs.

After installation, the log settings are managed via the user-editable C:\ProgramData\MySQL\MySQL Server [version number]\my.ini file. These settings include log names and paths as well as enable/disable switches.

For more information on collecting Microsoft MySQL logs, see our dedicated page to collecting and understanding MySQL Logs on windows.

Platform-Specific UNIX/Linux

The official distributions for individual UNIX/Linux platforms are typically script-based, with little or no interactive configuration during installation. Some installation packages (including Yum and APT) create the error log in /var/log/ or var/log/mysql/ with a name like error.log or mysqld.log. The data directory will typically be /var/lib/mysql/ or something similar, and it will serve as the default destination for any logs that are enabled without an alternate path.

The log settings are managed via a user-editable configuration file such as /etc/mysql/mysql.conf.d/mysqld.cnf. These settings include log names and paths as well as enable/disable switches. Startup and shutdown are typically managed by mysqld_safe (or with some distributions, systemd), which should find and apply log configuration options.

Generic UNIX/Linux

Generic installation is largely manual. During the installation process, you can enable and configure logs via the command line, by running scripts, or by editing the appropriate configuration file. The MySQL online reference manual (https://dev.mysql.com/doc/refman/5.7/en/server-logs.html) covers these options in detail.

The MySQL Error Log

The error log includes error messages, warnings, and notes generated during server operations as well as during the startup and shutdown phases; it also records startup and shutdown times.

The basic error log format is:

Error logging is always enabled, and the available options allow you to set the destination, verbosity level, and time zone.

Possible error log destinations are a file or the console. On Windows, if no destination option is specified, the error log is written to host_name.err (where host_name is the host system name) in the data directory. On UNIX/Linux systems, the default destination when no option is specified is the console.

For both UNIX/Linux and Windows-based MySQL installations, the —log-error option by itself (with no file name or path) sends the error log to host_name.err in the Data directory. If you specify the name and path (i.e., —log-error=»G:/TMP/mysql_logs/mysql_error.err» or —log-error=/var/log/mysql/error.log), the error log will be written to the specified file. In order to send the error log to the console on Windows, you must use the —console option; it overrides the —log-error option if both are present.

For more information regarding error logs and collecting them, see our page on Collecting logs in MySQL.

The General and Slow Query Logs

The general query and slow query logs both record user queries using a similar format: Time, ID, Command, and Argument (where Argument includes both the SQL commands and the data making up the query).

The general query log, however, records all client SQL statements along with connect and disconnect times, while the slow query log only records queries that take longer than the time specified by the long-query-time system variable. The slow query log also includes a set of fields containing the execution time, lock time, rows sent, and rows examined for each logged query.

Читайте также:  Во что форматировать флешку для linux

A typical general query log entry might look like this:

The slow query log entry for the same event might look like this:

The slow query log allows you to identify queries that require an unusually long time to execute; it may also be of use in uncovering system or database issues that result in slow execution. The general query log allows you to track all client SQL statements, which can be useful both for tracing errors and for identifying potential security problems.

The query logs tend to accumulate data rapidly, which may impact system performance in addition to taking up disk space. The general query log in particular can grow very quickly; both it and the slow query log are disabled by default in most installation packages. (The Windows MySQL installer, however, is an exception, as described above.)

The general query and slow query logs are enabled separately, using the —general-log and —slow-query-log options. The default destination is the data directory, with (host name].log and [host name]-slow.log as the file names. To set the log names and paths, use the —general-log-file and —slow-log-file options.

The format of both logs is controlled by a single option, —log-output, which takes the following values: FILE, TABLE, or NONE. FILE is the default value. TABLE stores both logs as tables, which can be read and managed via SQL queries. Both FILE and TABLE can be used together, separated by commas. NONE disables the output of both logs; if it is present, it overrides the other values.

Binary, Relay, and DDL Logs

The binary and relay logs are necessary for server replication, and the DDL log is used by the system to manage metadata during mysqld operation. These logs are generally of limited diagnostic use, although you may need to access binary and relay logs using the mysqlbinlog utility as part of the data recovery process.

Simplifying MySQL Log File location with Sumo Logic

The truth is that even with a relatively small number of server logs, MySQL can generate a lot of log data. At the same time, elements of that data may be important in terms of error-tracking, performance, and security. What’s the best way to organize and sort through MySQL server log data in order to find the things that you need to know?

The Sumo Logic App for MYSQL automatically picks out key metrics and data items from the error and slow query logs and presents them in easy-to-read dashboards. Sumo Logic makes it easy to identify performance issues, unusual behavior and activity patterns, and critical errors. You can check system health, replication status, and server performance at a glance, drilling down to detailed real-time information on slow queries (including origin by individual host, IP, and user), failed logins (by user, host, and location), and replication and server problems.

Don’t spend hours digging through log files — let Sumo Logic do the work for you so that you have time to get down to the business of serving your customers!

Complete visibility for DevSecOps

Reduce downtime and move from reactive to proactive monitoring.

Источник

Оцените статью