From cbd926362499dac8342b87259c760ba9e08727b8 Mon Sep 17 00:00:00 2001 From: snowdusk <31090558+snowdusk@users.noreply.github.com> Date: Wed, 16 Mar 2022 17:37:31 +0800 Subject: [PATCH] fix(log-rotate): should rotate logs strictly hourly(or minutely) (#6521) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: wangsong Co-authored-by: 帅进超 --- apisix/plugins/log-rotate.lua | 2 +- t/plugin/log-rotate2.t | 51 ++++++++++++++++++++++++++++++----- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/apisix/plugins/log-rotate.lua b/apisix/plugins/log-rotate.lua index 5b711c9dac10..79459371702e 100644 --- a/apisix/plugins/log-rotate.lua +++ b/apisix/plugins/log-rotate.lua @@ -243,7 +243,7 @@ local function rotate() local now_time = ngx_time() if not rotate_time then -- first init rotate time - rotate_time = now_time + interval + rotate_time = now_time + interval - (now_time % interval) core.log.info("first init rotate time is: ", rotate_time) return end diff --git a/t/plugin/log-rotate2.t b/t/plugin/log-rotate2.t index b04a6f52aae2..8f867e03e35b 100644 --- a/t/plugin/log-rotate2.t +++ b/t/plugin/log-rotate2.t @@ -25,14 +25,13 @@ no_root_location(); add_block_preprocessor(sub { my ($block) = @_; - my $user_yaml_config = <<_EOC_; + if (!defined $block->yaml_config) { + my $yaml_config = <<_EOC_; apisix: node_listen: 1984 - admin_key: null - -plugins: # plugin list + admin_key: ~ +plugins: - log-rotate - plugin_attr: log-rotate: interval: 1 @@ -40,7 +39,8 @@ plugin_attr: enable_compression: true _EOC_ - $block->set_value("yaml_config", $user_yaml_config); + $block->set_value("yaml_config", $yaml_config); + } if ((!defined $block->error_log) && (!defined $block->no_error_log)) { $block->set_value("no_error_log", "[error]"); @@ -138,3 +138,42 @@ start xxxxxx } --- response_body passed + + + +=== TEST 4: test rotate time align +--- yaml_config +apisix: + node_listen: 1984 + admin_key: ~ +plugins: + - log-rotate +plugin_attr: + log-rotate: + interval: 3600 + max_kept: 1 +--- config + location /t { + content_by_lua_block { + local log_file = ngx.config.prefix() .. "logs/error.log" + local file = io.open(log_file, "r") + local log = file:read("*a") + + local m, err = ngx.re.match(log, [[first init rotate time is: (\d+)]], "jom") + if not m then + ngx.log(ngx.ERR, "failed to gmatch: ", err) + return + end + + ngx.sleep(2) + + local now_time = ngx.time() + local interval = 3600 + local rotate_time = now_time + interval - (now_time % interval) + if tonumber(m[1]) == tonumber(rotate_time) then + ngx.say("passed") + end + } + } +--- response_body +passed