如何在 Nginx(healthd)中使用 access_log 文件名中的变量

如何在 Nginx(healthd)中使用 access_log 文件名中的变量

我在 AWS 中有一个多容器设置。我正在尝试遵循以下步骤: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-serverlogs.html

然而(使用最新的 Nginx - 1.9.12)当我尝试在文件名中使用变量时,我开始在错误日志中看到错误,并且文件本身并未创建。

错误日志:

2016/03/10 05:57:38 [error] 6#6: *1 testing "/etc/nginx/html" existence failed (2: No such file or directory) while logging request, client: xxx.xxx.xxx.xxx, server: localhost, request: "GET /v1/service?staus=ok HTTP/1.1", upstream: "http://xxx.xxx.xxx.xxx:8088/v1/service?staus=ok", host: "xxx.xxx.xxx.xxx"

此配置不起作用:

upstream app_v1 {
  server app_v1:8088;
}

map $http_upgrade $connection_upgrade {
  default        "upgrade";
  ""            "";
}

log_format healthd '$msec"$uri"'
          '$status"$request_time"$upstream_response_time"'
          '$http_x_forwarded_for';

server {
  listen 80;
  server_name localhost;

  gzip on;
  gzip_comp_level 4;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

  if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
    set $year $1;
    set $month $2;
    set $day $3;
    set $hour $4;
  }

  access_log /var/log/nginx/access.log main;
  access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;

  location ~* ^/ {
    proxy_pass         http://app_v1;
    proxy_redirect     off;

    proxy_set_header   Connection      $connection_upgrade;
    proxy_set_header   Upgrade         $http_upgrade;
    proxy_set_header   Host            $host;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

这个工作正常:

upstream app_v1 {
  server app_v1:8088;
}

map $http_upgrade $connection_upgrade {
  default        "upgrade";
  ""            "";
}

log_format healthd '$msec"$uri"'
          '$status"$request_time"$upstream_response_time"'
          '$http_x_forwarded_for';

server {
  listen 80;
  server_name localhost;

  gzip on;
  gzip_comp_level 4;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

  access_log /var/log/nginx/access.log main;
  access_log /var/log/nginx/healthd/application.log healthd;

  location ~* ^/ {
    proxy_pass         http://app_v1;
    proxy_redirect     off;

    proxy_set_header   Connection      $connection_upgrade;
    proxy_set_header   Upgrade         $http_upgrade;
    proxy_set_header   Host            $host;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

然而,healthd 服务(增强健康)正在寻找格式如下的文件:

/var/log/nginx/healthd/application.log.$year-$month-$day-$hour

我可以使用 docker-compose 在本地重现此操作。我不确定我在这里遗漏了什么。

马克西姆

答案1

这是一个常见的陷阱。Docaccess_log说:

文件路径可以包含变量(0.7.6+),但是此类日志有一些限制:

  • ...
  • 每次写入日志时,请求的根目录检查,如果不存在,则日志未创建

您没有设置根目录,因此 nginx 恢复为默认目录,/etc/nginx/html并且该目录不存在。

只需添加root /var/www;(或其他现有路径)或者按照 zezollo 建议的那样创建/etc/nginx/html

相关内容