nginx-3:日志配置

参考:https://blog.csdn.net/qq_29677867/article/details/90112754

 

一、nginx access 日志配置

 

1. access_log 日志配置

  access_log 用来定义日志级别,日志位置。

  日志级别:debug > info > notice > warn > error > crit > alert > emerg

  

  语法格式:

  access_log path [format [buffer=size]] [gzip[=level]] [flush=time] [if=condition];

  access_log off;

  默认值:access_log logs/access.log combined;

  作用域:http、server、location、if in location、limit_except

  例如:access_log /var/logs/nginx-access.log compression buffer=32k;

 

2. log_format 定义日志格式

  语法格式:log_format name [escape=default|json] ...;

  默认值:log_format combined '...';

  作用域:http

  例如:log_format compression '$remote_addr - $remote_user [$time_local] '

                '"$request" $status $bytes_sent '

                '"$http_referer" "$http_user_agent" "$gzip_ratio" ';

  access_log /var/logs/nginx-access.log compression buffer=32k;

 

3. open_log_file_cache

  使用 open_log_file_cache 来设置日志文件缓存(默认是 off)。将多个日志进行积累,达到一定量级后写入到磁盘,可以减少磁盘旋转,从而降低磁盘 io ,提升 nginx 能效。

  • max:设置缓存中最大文件描述符数量,如果缓存被占满,采用 LRU 算法将描述符关闭
  • inactive:设置存活时间,默认是 10s
  • min_uses:设置在 inactive 时间段内,日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是 1 次
  • valid:设置检查频率,默认 60s
  • off:禁用缓存

  语法格式:

  open_log_file_cache max=N [inactive=time] [min_uses=N] [calid=time];

  open_log_file_cache off;

  作用域:http,server,location

  例如:

  open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

 

4. 日志中常用的全局变量

  

 

   随用随取

 

二、nginx 日志调试技巧

 

1. 仅记录固定 IP 的错误

  当日志级别是 debug,如果在调试一个在线的高流量网站的话,错误日志可能会记录每个请求的很多消息,变得毫无意义。

  在 event{...} 中配置如下内容,可以使 nginx 记录仅仅来自特定 IP 的错误日志

  event{

    debug_connection 1.2.3.4;

  }

 

2. 调试 nginx rewrite 规则

  rewrite 是实现 URL 重定向的重要指令,他根据 regex 来匹配内容跳转到 replacement,结尾是 flag 标记。

  调试 rewrite 规则时,如果规则写错只会看见一个 404 页面,可以在配置文件中开启 nginx rewrite 日志,进行调试。

  server {

    error_log /var/logs/nginx/xxx.log

    rewrite_log on;

  }

  rewrite_log on;   开启后,它将发送所有的 rewrite 相关的日志信息到 error_log 文件中,使用 [notice] 级别。随后就可以在 error_log 查看 rewrite 信息了。

 

3. 使用 location 记录指定 URL 的日志

  server {

    error_log  /var/logs/nginx/xxx.log;

    location  /static/ {

      error_log  /var/logs/nginx/xxx-static.log  debug;

    }

  }

  配置以上配置后,/static/ 相关的日志会被单独记录在 xxx-static.log 文件中

  nginx 日志共三个参数

  1)access_log:定义日志的路径和级别

  2)log_format:定义日志的模板

  3)open_log_file_cache:定义日志文件缓存

  

  proxy_set_header X-Forwarded-For:如果后端 web 服务器上的程序需要获取用户 IP,从该 Header 头获取。proxy_set_header X-Forwarded-For $remote_addr;

 

posted @ 2020-08-19 17:00  停不下的时光  阅读(262)  评论(0编辑  收藏  举报