nginx map 妙用

动态代理

worker_processes auto;
...
stream {
  map $remote_addr $dynamic_backend
    xxx.xxx.xxx.xx1  "test1";
    xxx.xxx.xxx.xx2  "test2";
    xxx.xxx.xxx.xx3  "test3";
    default "test1"

  upstream test1 {
    server xxx.xxx.xxx.xxx:80;
  }
  upstream test2 {
    server xxx.xxx.xxx.xxx:80;
  }
  upstream test3 {
    server xxx.xxx.xxx.xxx:80;
  }
  server {
    listen 80;
    proxy_pass $dynamic_backend
  }
}
http {
  ...
}

access日志添加颜色

http{
  map  $request_time $request_time_format {
    default "";
  }
  map  $status $status_format {
    default "";
  }
  log_format main escape=none '$remote_addr $time_iso8601 $msec $request_time_format $status_format'
  
  server {
    location / {
       ...
    }
    log_by_lua_file  'conf/lua_deal_log.lua'  # 需要 nginx 安装 lua-Nginx-module 支持
  }
}

lua_deal_log.lua

local request_time = tonumber(ngx.var.request_time)
local status = tonumber(ngx.var.status)
ngx.var.request_time_format = ngx.var.request_time
ngx.var.status_format = ngx.var.status
 
--处理时间
if request_time < 0.01 then
    ngx.var.request_time_format = ngx.var.request_time
elseif request_time >= 0.01 and request_time < 0.1 then
    // [0;36;40m   [0m   linux 颜色符号,  更多颜色符号 ps1加颜色(linux输入命令行添加颜色) 文章中涉及的有
    ngx.var.request_time_format = string.char(0x1b) .. "[0;36;40m" .. ngx.var.request_time .. string.char(0x1b) .. "[0m"
elseif request_time >= 0.1 and request_time < 0.5 then
    ngx.var.request_time_format = string.char(0x1b) .. "[0;33;40m" .. ngx.var.request_time .. string.char(0x1b) .. "[0m"
else
    ngx.var.request_time_format = string.char(0x1b) .. "[0;31;40m" .. ngx.var.request_time .. string.char(0x1b) .. "[0m"
end
 
--处理状态码
if status >= 500 then
    ngx.var.status_format = string.char(0x1b) .. "[0;31;40m" .. status .. string.char(0x1b) .. "[0m"
elseif status >= 400 then
    ngx.var.status_format = string.char(0x1b) .. "[0;33;40m" .. status .. string.char(0x1b) .. "[0m"
elseif status < 100 then
    ngx.var.status_format = string.char(0x1b) .. "[0;36;40m" .. status .. string.char(0x1b) .. "[0m"
end

你可能感兴趣的:(nginx map 妙用)