概述

一些Nginx日志需要过滤, 比如监控经常以分钟为单位检测网站导致日志过多

解决方法

.conf文件的http节点下增加如下

# 定义格式化日志main, 此处为NGINX默认日志格式
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

                     '$status $body_bytes_sent "$http_referer" '

                     '"$http_user_agent" "$http_x_forwarded_for"';
# 生成health Map变量, 默认1, 匹配到$http_user_agent 含有以Uptime-Kuma开头的则设置为0
map $http_user_agent $health {

	~^Uptime-Kuma 0;

	default 1;

}
# 如果按main定义的规则, 如果$health不等于1则不输出到日志文件, 该内容也可到server节点下
access_log /usr/local/nginx/logs/main-and-freshrss.log main if=$health;

使用if判断

以下逻辑其实是的实现, 但nginx中并没有逻辑判断, 只能采取折中法

# 默认写入

    set $write 1;

    # 是否将主题静态资源访问日志写入

    if ($request ~* ".*/themes/.*" ){

        set $write 0;

    }

    # 是否将uptime-kuma心跳日志写入

    if ($health = "0"){

        set $write 0;

    }

    access_log /usr/local/nginx/logs/main-and-freshrss.log main if=$write;

    error_log /usr/local/nginx/logs/main-and-freshrss.error.log;

参考资料