V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
shanghai1943
V2EX  ›  问与答

NGINX 如何记录 localhost 的访问日志

  •  
  •   shanghai1943 · 2022-10-12 12:33:52 +08:00 · 599 次点击
    这是一个创建于 556 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我在 /etc/nginx/conf.d 目录下新建了 一个 localhost.conf 配置文件,内容如下

    server {

       listen 12345;
    
       server_name localhost 127.0.0.1;
    
       access_log /var/log/nginx/localhost.log main;
    

    }

    nginx -t 和 nginx -s reload 之后,在同台机器用 curl 发起了请求

    curl http://localhost:12345/abc

    以及

    curl http://127.0.0.1:12345/abc

    在 /var/log/nginx 目录下能看到 localhost.log 文件,但是没有任何内容。

    有大佬能指点一下的么?谢谢。

    第 1 条附言  ·  2022-10-13 12:24:57 +08:00
    最终解决方案:

    localhost.conf 里改为监听+转发的模式,即,监听端口 12345 ,然后转发到端口 123456

    server {

    listen 12345;

    server_name localhost 127.0.0.1;

    location / {

    proxy_pass http://localhost:123456;

    access_log /var/log/nginx/localhost.log main;

    error_log /var/log/nginx/error.log warn;

    }

    }

    在 localhost.log 里看到有相应的请求日志了。

    感谢。
    5 条回复    2022-10-13 13:05:22 +08:00
    iPc666
        1
    iPc666  
       2022-10-12 19:31:24 +08:00   ❤️ 1
    估计是访问不存在,走到了 errorlog 里。去 /var/log/nginx/下的 error.log 里找
    shanghai1943
        2
    shanghai1943  
    OP
       2022-10-13 10:13:16 +08:00
    @iPc666 #1 在 /var/log/nginx/ 下 grep abc * 啥都没有。。
    iPc666
        3
    iPc666  
       2022-10-13 11:16:10 +08:00
    在 access_log 后面加上这句话

    # Logging
    error_log /var/log/nginx/error.log warn;
    log_format main '$remote_addr - [$time_local] "$request" "$request_time" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for" "$request_length" "$http_host"';
    shanghai1943
        4
    shanghai1943  
    OP
       2022-10-13 11:39:25 +08:00
    @iPc666 #3 貌似还是不行。error.log 里没有相应的错误信息。 另:log_format 这个不支持在 server directive 里添加,所以就没加。

    nginx: [emerg] "log_format" directive is not allowed here in /etc/nginx/conf.d/localhost.conf:9
    iPc666
        5
    iPc666  
       2022-10-13 13:05:22 +08:00
    加在 nginx.conf 的 http 里试试

    nginx.conf 文件

    http {
    其他配置....

    # Logging
    error_log /var/log/nginx/error.log warn;
    log_format main '$remote_addr - [$time_local] "$request" "$request_time" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for" "$request_length" "$http_host"';
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2852 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:06 · PVG 21:06 · LAX 06:06 · JFK 09:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.