You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

开启MySQL慢查询日志时遭遇权限拒绝及SELinux上下文配置错误求助

Fixing MySQL Slow Query Log Permission & SELinux Errors

Hey there, let's work through this slow query log issue you're hitting. The errors you're seeing are a mix of file permissions and SELinux context problems—here's how to resolve them step by step:

1. Ensure the Log File Exists with Correct Basic Permissions

First, make sure you're running these commands as root (use sudo if you're not logged in as root):

  • Create the log file if it doesn't exist:
    touch /var/log/mysqld_slow.log
    
  • Set the correct ownership to the MySQL user/group (this is critical—MySQL needs to read/write to this file):
    chown mysql:mysql /var/log/mysqld_slow.log
    
  • Set secure file permissions (640 is sufficient; avoid 666 as it exposes the log to too many users):
    chmod 640 /var/log/mysqld_slow.log
    

2. Fix the SELinux Context Error

The chcon: can't apply partial context to unlabeled file error happens because the new log file doesn't have an initial SELinux label. Here are two reliable fixes:

Option A: Restore Default Label First, Then Apply MySQL Log Context

  1. Restore the file's default SELinux label (this gives it a baseline context):
    restorecon -v /var/log/mysqld_slow.log
    
  2. Now apply the MySQL log-specific context:
    chcon -t mysqld_log_t /var/log/mysqld_slow.log
    

The above fix might reset after a system reboot. To make the context permanent:

  1. Add a persistent SELinux file context rule:
    semanage fcontext -a -t mysqld_log_t "/var/log/mysqld_slow.log"
    
  2. Apply the rule to the file:
    restorecon -v /var/log/mysqld_slow.log
    

Verify the SELinux Context

Run this command to confirm the context is set correctly:

ls -Z /var/log/mysqld_slow.log

You should see mysqld_log_t in the output.

3. Enable Slow Query Log (Temporary & Permanent)

  • Temporary enable (only lasts until MySQL restarts):
    set global slow_query_log = 'ON';
    
  • Permanent enable (survives restarts):
    Edit your MySQL config file (usually /etc/my.cnf or /etc/mysql/my.cnf) and add these lines:
    slow_query_log = 1
    slow_query_log_file = /var/log/mysqld_slow.log
    long_query_time = 2  # Adjust this to your threshold (e.g., 2 seconds for slow queries)
    
    Then restart MySQL:
    systemctl restart mysqld
    

Alternative: Use MySQL's Default Log Directory

If SELinux is still giving you trouble, consider placing the slow query log in MySQL's default data directory (typically /var/lib/mysql/). This directory already has the correct SELinux context for MySQL files:

set global slow_query_log_file = '/var/lib/mysql/mysqld_slow.log';
set global slow_query_log = 'ON';

For permanent setup, update the slow_query_log_file path in your MySQL config to this location.

内容的提问来源于stack exchange,提问作者Fred

火山引擎 最新活动